I want to get the name of the images in the trip version in show.blade.php
but for some reason I can't get someone to help me
App\Models\Images
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Images extends Model
{
use HasFactory;
protected $fillable = [
'id',
'name',
'trip_id',
];
public function trip()
{
return $this->belongsTo(Trip::class);
}
}
App\Models\Trip
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Trip extends Model
{
use HasFactory;
protected $fillable = [
'title',
'place',
'tripcontent',
'user_id'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function images()
{
return $this->hasMany(Images::class);
}
}
App\Http\Controllers\TripController
namespace App\Http\Controllers;
use App\Models\Trip;
use App\Models\Images;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Auth;
public function show(Trip $trip)
{
return view('trip.show')->with([
'trip' => $trip,
]);
}
resources\views\trip\show.blade.php
<div class="col-sm-6 col-md-4 col-lg-3 mt-2">
<img class="img-fluid" src="/img/trip/{{ $trip->images->name}}.jpg"">
</div>
That's how I want to get the data in view
$trip-> images-> name
Someone can help
Related
I have been having this problem for the past week, I have searched everywhere but wasn't able to find a problem.
My service
private texst!: Posts[];
public getPosts(): Observable<Posts[]>
{
return this.http.get<Posts[]>("http://localhost/projects/php_rest_api/api/post/read.php").pipe(map((data) => {
return this.texst = data;
}));
}
My Component, here i add the service and run the function to get the data from my database
public test: Posts[] = [];]
constructor(public postService: PostsService,
private http: HttpClient) {}
ngOnInit(): void {
this.getPosts();
}
public getPosts()
{
this.postService.getPosts().subscribe((response) => {
this.test = response;
console.log(this.test);
})
}
My html
<div>
<button (click)="getPosts()"></button>
<div *ngFor="let test of test">
{{test.title}}
</div>
</div>
Change this, rename your var test to testItem because it's already used:
<div>
<button (click)="getPosts()"></button>
<div *ngFor="let testItem of test">
{{testItem.title}}
</div>
</div>
Managed to fix it
changed the response to object.values in my getPosts() function
public getPosts()
{
this.postService.getPosts().subscribe((response) => {
this.test = Object.values(response);
console.log(this.test);
})
}
It means you're trying to iterate over object, but you think it's an array.
If that image is a log of the response, you better do:
public getPosts()
{
this.postService.getPosts().subscribe((response) => {
this.test = response.data; // <.. this changes!
})
}
and in template:
<div *ngFor="let testItem of test">
{{testItem.title}}
</div>
I get the data from an API with the service game in game.component.ts I get the data I can show in cards the array of objects games but i am geting this error:
core.js:6241 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
at NgForOf.ngDoCheck (common.js:4406)
also the model Game{name:"",image:"",releaseOn:Array(0)......} it is empty the model is not being used.
export class GamesService {
public url;
public game: Game[];
constructor(
private http: HttpClient
) { }
getListGames():Observable<any>
{
return this.http.get(`https://api.rawg.io/api/games?&dates=2010-01-01,2020-12-31&page_size=20`);
}
to the component games.component.ts
export class GamesComponent implements OnInit {
public games: Game;
//public game: Game;
public genres;
public platforms;
public pcIcon: string = '../assets/pc.png';
public PC;
public Xbox: string = '../assets/xbox.png';
public plat: string;
public name: string;
public title = 'Games component';
//public carouselExampleControls: String;
//public index: number;
public rating;
public page: number = 1;
public totalPages;
public next;
public prev;
public number_pages;
public count;
public nextpage;
constructor(
private gamesService:GamesService,
private router: Router,
)
{
this.games = new Game('', '', [], '', [], 1 );
console.log(this.games);
}
ngOnInit(): void {
this.gamesService.getListGames().subscribe( (data: any) =>{
this.games = data.results;
console.log(data.results[0].platforms[0]);
data.results.forEach((game) => {
game.platforms.forEach((platform)=> {
//your code here
console.log(platform);
});
});
});
}
How to get the object game from the api using the model game.ts
game.ts
export class Game{
id: any;
constructor(
public name: string,
public image: string,
public releaseOn: Array<ReleaseOn>,// do it an array of releaseOn platform
public releaseDate: string,
public genre: Array<Genres>,// do it an array of genres
public rating: number,
){}
}
export class Genres {
genre: string
}
export class ReleaseOn {
releaseOn: string
}
How to get the data from API with game.ts model in game.component
this.games = new Game('', '', [], '', [], 1 );
game-card.component.ts
<div class="card">
<h5 class="card-title">
{{ games.name}}
</h5>
<img class="card-img-top" [src]="games.background_image" alt="Card image cap">
<div class="card-body">
<!-- <p class="card-text"><span class="black">Release on</span> {{ game.platform.name}}</p> -->
<p class="card-text"><span class="black">Release on</span> <span class="platform" *ngFor="let platforms of games.platforms"><img class="img-icon" *ngFor="let platforms of games.platforms.name"> {{ platforms.platform.name }}</span></p>
<p class="card-text"><span class="black">Release date</span> {{ games.released }}</p>
<p class="card-text"><span class="black">Genere </span><span class="platform" *ngFor="let genres of games.genres">{{ genres.name}}</span></p>
<p class="card-text"><span class="black">Rating <star-rating [value]="games.rating" totalstars="5" checkedcolor="yellow" uncheckedcolor="black" size="24px" readonly="false"></star-rating></span></p>
<p class="card-text">
<span class="badge badge-primary">
{{ games.user_game }}
</span>
</p>
<div>
object game from api
As data model and view model are different, You need to map each property.
Try this. I have not tested it but it should work.
this.gamesService.getListGames().subscribe( (data: any) =>{
this.games = data.results.map(item=>{
const gameItem: Game = {
id: item.id,
name: item.name,
image: item.background_image,
releaseDate: item.released,
rating: item.rating,
genre: item.genres ? item.genres.map(g => ({ genre: g.name })) : [],
releaseOn: item.platform
? item.platform.map(p => ({ releaseOn: p.name }))
: []
};
return gameItem;
});
});
I am using this code
var parent = ContentReference.StartPage;
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
PageData myPage = contentRepository.GetDefault<LoginPage>(parent);
myPage.PageName = "My new page";
var page = contentRepository.GetChildren<LoginPage>(parent).FirstOrDefault(name => name.Name == myPage.Name);
if (page == null)
contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish);
to create a page programatically. The thing is I am not sure where to put this code?
I don't want to show LoginPage which is page type to show in the list in the admin/edit panel as I want to create only one page under that page type. Maybe there is another way where I can just create a stand alone page and don't have to create the page type or maybe use an already made page type.
This is the code for my page type
[ContentType(DisplayName = "Custom Login Page", GUID = "c0d358c3-4789-4e53-bef3-6ce20efecaeb", Description = "")]
public class LoginPage : StandardPage
{
/*
[CultureSpecific]
[Display(
Name = "Main body",
Description = "The main body will be shown in the main content area of the page, using the XHTML-editor you can insert for example text, images and tables.",
GroupName = SystemTabNames.Content,
Order = 1)]
public virtual XhtmlString MainBody { get; set; }
*/
}
Then I am creating a model like this
public class LoginModel : PageViewModel<LoginPage>
{
public LoginFormPostbackData LoginPostbackData { get; set; } = new LoginFormPostbackData();
public LoginModel(LoginPage currentPage)
: base(currentPage)
{
}
public string Message { get; set; }
}
public class LoginFormPostbackData
{
public string Username { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
public string ReturnUrl { get; set; }
}
And my controller looks like this
public ActionResult Index(LoginPage currentPage, [FromUri]string ReturnUrl)
{
var model = new LoginModel(currentPage);
model.LoginPostbackData.ReturnUrl = ReturnUrl;
return View(model);
}
Do you think there is another way to do it? I will also show my login view
#using EPiServer.Globalization
#model LoginModel
<h1 #Html.EditAttributes(x =>
x.CurrentPage.PageName)>#Model.CurrentPage.PageName</h1>
<p class="introduction" #Html.EditAttributes(x =>
x.CurrentPage.MetaDescription)>#Model.CurrentPage.MetaDescription</p>
<div class="row">
<div class="span8 clearfix" #Html.EditAttributes(x =>
x.CurrentPage.MainBody)>
#Html.DisplayFor(m => m.CurrentPage.MainBody)
</div>
#if (!User.Identity.IsAuthenticated &&
!User.IsInRole("rystadEnergyCustomer"))
{
<div class="row">
#using (Html.BeginForm("Post", null, new { language = ContentLanguage.PreferredCulture.Name }))
{
<div class="logo"></div>
#Html.AntiForgeryToken()
<h2 class="form-signin-heading">Log in</h2>
#Html.LabelFor(m => m.LoginPostbackData.Username, new { #class = "sr-only" })
#Html.TextBoxFor(m => m.LoginPostbackData.Username, new { #class = "form-control", autofocus = "autofocus" })
#Html.LabelFor(m => m.LoginPostbackData.Password, new { #class = "sr-only" })
#Html.PasswordFor(m => m.LoginPostbackData.Password, new { #class = "form-control" })
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.LoginPostbackData.RememberMe)
#Html.DisplayNameFor(m => m.LoginPostbackData.RememberMe)
</label>
</div>
#Html.HiddenFor(m => m.LoginPostbackData.ReturnUrl, "/login-customers")
<input type="submit" value="Log in" class="btn btn-lg btn-primary btn-block" />
}
#Html.DisplayFor(m => m.Message)
</div>
}
else
{
<span>Welcome #User.Identity.Name</span>
#Html.ActionLink("Logout", "Logout", "LoginPage", null, null);
}
I think you're misunderstanding some of the Episerver concepts.
If you don't want it to be a page in Episerver, you shouldn't use PageController, page types, or templates. Instead, just use a standard controller and view to create your login page.
Otherwise, you do have to create a page of type LoginPage, which will be visible in the page tree. No need to create it programmatically, you can just add the page manually and then hide the LoginPage type from edit mode to avoid editors creating additional login pages.
I've got the following directive (I've cut out the non-important part for the sake of brevity) :
I basically use the ng-include directive to dynamically load my templates.
Directive
module chat.directives {
"use strict";
export class ChatWindow implements ng.IDirective {
public restrict = 'E'
public static DirectoryName = "chatWindow";
public scope = {
chatModel: '=',
chatSection: '#chatSection'
}
public template(element : ng.IAugmentedJQuery, attrs : IChatWindowAtributes) {
return '<div ng-include="getTemplateUrl()"></div>';
}
public link(scope:chat.controllers.IChatScope, element:ng.IAugmentedJQuery, attrs:ng.IAttributes) {
scope.getTemplateUrl = () => {
return "/chat/directives/" + scope.chatSection + "-chat-window-template.html";
}
}
public static factory():ng.IDirectiveFactory {
var directive = () => new ChatWindow();
directive.$inject = [];
return directive;
}
}
interface IChatWindowAtributes extends ng.IAttributes {
chatSection : string;
}
angular
.module('chat')
.directive(chat.directives.ChatWindow.DirectoryName, chat.directives.ChatWindow.factory());
}
Problems do arise as soon as I try to implement an event in one of the templates, for example ng-click.
Because I am using the ng-include hack, element.html() of the linkage function refers to <div ng-include="getTemplateUrl()"></div> and thus doesn't allow me to setup an eventhandler programmatically.
HTML Template
<!-- Chat window-->
<div class="col-xs-4 chat-window">
<aside>
<div class="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-list-alt icon"></span>
</div>
<div class="chat-output">
</div>
<form action="">
<input id="msgInput" autocomplete="off"/>
<button ng-click="chat.sendMessage('hi')" stop-event>Send</button>
</form>
</div>
</aside>
</div>
Additionally, any call from the template with ng-click="chat.sendMessage('hi')" doesn't trigger the corresponding function in my controller.
Controller Implementation
module chat.controllers {
'use strict';
class ChatCtrl {
public chatHistory : Array<Common.Services.IMessage> = [];
public chatSection : string;
public currentMessage : string;
// $inject annotation.
// It provides $injector with information about dependencies to be injected into constructor
// it is better to have it close to the constructor, because the parameters must match in count and type.
// See http://docs.angularjs.org/guide/di
public static $inject = [
'$scope',
'UserService',
'MessageService'
];
// dependencies are injected via AngularJS $injector
constructor(private $scope: IChatScope, private userService : User.Services.IUserService, private messageService : Common.Services.IMessageService) {
this.$scope.chatModel = {
chatHistory: this.chatHistory,
userService : this.userService,
messageService: this.messageService,
storeChatSectionInCtrl : this.storeChatSectionInCtrl,
subscribeToChatSectionEvents : this.subscribeToChatSectionEvents,
fetchChatHistory : this.fetchChatHistory
}
}
public storeChatSectionInCtrl(section){
// Store the section additionally to the directive in the controller
this.chatSection = section;
}
public subscribeToChatSectionEvents(section : string){
var self = this;
// Subscribe for the chat section for incoming messages
this.messageService.addMessageListener(section + "ChatMessage", function(){
});
// Subscribe for incoming messages to load the chat history
this.messageService.addMessageListener(section + "ChatHistory", function(message : ChatHistoryMessage){
self.chatHistory = message.data.chatHistory;
});
}
// Send a chat message to the server
public sendMessage(message : string){
var messageObj = new ChatInputMessage({
chatSectionPrefix : this.chatSection,
chatMessageObj : new ChatMessage({
message : message
})
});
this.messageService.sendMessage(messageObj);
}
// Send a request for the chat history to the server
public fetchChatHistory(section : string){
var messageObj : ChatHistoryMessage = new ChatHistoryMessage({
chatSectionPrefix : section,
chatHistory : null
});
// Send a request in order to retrieve the chat history of the given section
this.messageService.sendMessage(messageObj);
}
}
export interface IChatScope extends ng.IScope {
getTemplateUrl : () => string;
chatModel : IChatModel;
chatSection : string;
}
export interface IChatModel {
chatHistory : Array<Common.Services.IMessage>;
userService: User.Services.IUserService;
messageService : Common.Services.IMessageService;
storeChatSectionInCtrl : (section : string) => void;
subscribeToChatSectionEvents: (nameOfEventListener : string) => void;
fetchChatHistory : (section: string) => void;
}
// Message
export interface IChatMessage {
message : string;
creationDate? : string;
from? : string;
to? : string;
}
export class ChatMessage implements IChatMessage {
public message : string;
public creationDate : string;
public from : string;
public to : string;
constructor(message : IChatMessage){
this.message = message.message;
this.creationDate = message.creationDate;
this.from = message.from;
this.to = message.to;
}
};
// Message Service
export interface IChatData{
chatSectionPrefix : string;
chatMessageObj : IChatMessage;
}
export class ChatInputMessage extends Common.Services.ClientMessage<IChatData> {
static NAME = "ChatMessage";
constructor (chatData: IChatData) {
super(chatData.chatSectionPrefix + ChatInputMessage.NAME, chatData);
}
}
// Chat history
export class ChatHistoryMessage extends Common.Services.ClientMessage<IChatHistory> {
static NAME = "ChatHistory";
constructor (chatData: IChatHistory) {
super(chatData.chatSectionPrefix + ChatHistoryMessage.NAME, chatData);
}
}
export interface IChatHistory{
chatSectionPrefix : string;
chatHistory : Array<IChatMessage>;
}
/**
* #ngdoc object
* #name chat.controller:ChatCtrl
*
* #description
*
*/
angular
.module('chat')
.controller('ChatCtrl', ChatCtrl);
}
HTML
<div ng-controller="ChatCtrl">
<chat-window chat-model="chatModel" chat-section='lobby'></chat-window>
</div>
Solution
For some reason I though I would operate on the controller instead of the directive - thus using sendMessage('hi') instead of chat.sendMessage('hi') solved the issue ...
I am looking for a VERY simple example that shows wiring up Knockback code to a backbone model that connects via RESTful service. I am using ServiceStack|c# backend. All of the links below are too complicated and use localStore rather than a RESTful service via url. I also prefer to see examples in Javascript not CoffeeScript.
My example url is something like localhost/entities where hitting this will cause the RESTful webservice to return all of the entities. Hitting it with localhost/entity/1 would return the entity with an Id of 1.
_http://kmalakoff.github.com/knockback/index.html
_https://github.com/kmalakoff/knockback-reference-app/
_https://github.com/addyosmani/todomvc
The following is the example from knockback tutorial on the first link:
Models, Collection, ViewModel, and Bindings:
// Generated by CoffeeScript 1.3.3
var model, view_model;
model = new Backbone.Model({
first_name: "Planet",
last_name: "Earth"
});
view_model = kb.viewModel(model);
view_model.full_name = ko.computed((function() {
return "" + (this.first_name()) + " " + (this.last_name());
}), view_model);
ko.applyBindings(view_model, $('#kb_view_model_computed')[0]);
But there is no mention of how you would wire the backbone model up to your RESTful webservice.
There are examples of how do this via Backbone but I am uncertain as to how things change when using Knockback.
The following links were found, but not helpful:
_http://stackoverflow.com/questions/7992431/using-knockoutjs-backbone-together
_http://stackoverflow.com/questions/9704220/is-knockback-js-production-ready
_http://stackoverflow.com/questions/10434203/defining-models-on-server-side-when-using-mvvm-with-knockout-js
Thanks in advance for any assistance provided. Btw you don't want hyperlinks you get underscores... ;)
With much help and support from Kevin Malakoff from the great Knockback project I was able to get a small example working! I used the ServiceStack Backbone Todos project as a starting point.
c# file: Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using ServiceStack.Redis;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
namespace MyApp
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonService : RestServiceBase<Person>
{
public static Person kevin = new Person { Id = 1, FirstName = "Kevin", LastName = "Malakoff" };
public static Person scott = new Person { Id = 2, FirstName = "Scott", LastName = "Idler" };
public static List<Person> people = new List<Person> { kevin, scott };
public override object OnGet(Person person)
{
if (person.Id != default(int))
return people[person.Id-1];
return people;
}
public override object OnPost(Person person)
{
return base.OnPost(person);
}
public override object OnPut(Person person)
{
return OnPost(person);
}
public override object OnDelete(Person person)
{
return base.OnDelete(person);
}
}
public class AppHost : AppHostBase
{
public AppHost() : base("MyApp", typeof(PersonService).Assembly) { }
public override void Configure(Funq.Container container)
{
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
Routes
.Add<Person>("/persons")
.Add<Person>("/persons/{Id}");
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
new AppHost().Init();
}
}
}
html file: default.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MyApp2</title>
<script>window.JSON || document.write('<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">\x3C/script>')</script>
<script src="Scripts/jquery-1.8.0.js" type="text/javascript" ></script>
<script src="Scripts/knockback-full-stack-0.16.1.js" type="text/javascript" ></script>
<script src="myapp.js" type="text/javascript" ></script>
</head>
<body>
<div id="myapp">
<div class="title">
<h1>MyApp</h1>
</div>
<div class="content">
<div id='kb_observable'>
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
<p>Hello, <span data-bind="text: fullName"></span>!</p>
</div>
<div id="kb_collection_observable">
<div data-bind="if: persons">
<span>Has Persons</span>
</div>
<div data-bind="foreach: persons">
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
</div>
</div>
</div>
</div>
</body>
</html>
javascript file: myapp.js
$(function() {
//model
var PersonModel = Backbone.Model.extend({ urlRoot: '/MyApp/persons' });
var model = new PersonModel({ id: 1 });
model.fetch();
//viewmodel
var PersonViewModel = function (person) {
this.firstName = kb.observable(person, 'firstName');
this.lastName = kb.observable(person, 'lastName');
this.fullName = ko.computed((function () {
return "" + (this.firstName()) + " " + (this.lastName());
}), this);
};
var personViewModel = new PersonViewModel(model);
//binding
ko.applyBindings(personViewModel, $('#kb_observable')[0]);
//model
var PersonsModel = Backbone.Collection.extend({ model: PersonModel, url: '/MyApp/persons' });
var personsModel = new PersonsModel();
personsModel.fetch();
//viewmodel
var PersonsViewModel = function (persons) {
this.persons = kb.collectionObservable(persons)
};
var personsViewModel = new PersonsViewModel(personsModel);
//binding
ko.applyBindings(personsViewModel, $('#kb_collection_observable')[0]); });
I put together a very simple example. It assumes you already know how to use backbone and knockout so this just gives a quick example of how they can be used together
http://coder2.blogspot.com/2013/02/backbonejs-and-knockoutjs.html