Steer clear of displaying the latest model directly

Currently, I have a form for creating a new Model named Route. This form includes a select field called takeover, which displays all existing Routes for the user to choose from and establish a relationship with the selected Route. The issue I am facing is that the newly created Route is also appearing in the select field, because I am using 'this.get('store').findAll('routes')' method. How can I prevent the newly created Model from being displayed in the selection dropdown, as it is not possible to create a relationship with itself.

Within the Route file, I start by initializing an empty Model which users can then fill out using the form:

//route.js
model() {
    return this.store.createRecord('route', {});
  },

Template:

//route.hbs
<form>
//input fields
//select-component code:
{{my-select
    selected=model.takeover
    options=routes
}}
</form>

The routes available for selection are defined within the route file:

//route.js
 routes: Ember.computed(function () {
    return this.get('store').findAll('route');
  }).readOnly(),

At the moment, the list of selectable options includes all routes, including the new model. However, it should not be possible to select the model itself, so I need to remove it from the options. How can I achieve this?

Answer №1

A computed property can be utilized to filter out records that are not new.

routes: Ember.computed.filterBy('model', 'isNew', false)

The isNew property is true for models that have not been saved yet using .save(). More information can be found here:

It is advisable to keep the store request separate from the computed property (CP) used for filtering the list. The logic for making a request to the backend/store should remain in the model hook, while the CP for filtering can reside in the controller where the result is sent.

Edit made in response to a comment:

The "Ember way"

In Ember, it is preferred for requests to the backend to be handled in the route file. The route has access to the store and provides built-in async error handling. Typically, you would make the request in the model hook like so:

// route.js
model() {
  return this.get('store').findAll('route');
}

If you need to create a new record as well, you can do it as follows:

// route.js
model() {
  this.get('store').createRecord('route');
  return this.get('store').findAll('route');
}

The result of the model hook is passed to the setupController method, which automatically builds the controller object. The controller then communicates the model to the view by default:

setupController(controller, model) {
  controller.set('model', model);
}

Adding a computed property to the controller can now be done. If there isn't a controller.js file by default, one can be generated with Ember-CLI:

ember g controller <route-name>

Since the model was passed to our controller, we can create a computed property to filter the model:

// controller.js
routes: Ember.computed.filterBy('model', 'isNew', false)

This will provide an array of all the route records that are not "new." Now the view should have access to routes.

//route.hbs
<form>
//some fields
//and a select-component:
{{my-select
    selected=model.takeover
    options=routes
}}
</form>

If unsure about what model.takeover refers to, similar filtering can be applied to retrieve only the record that is considered new based on the isNew property.

Answer №2

Give this a shot,

routes: Ember.computed(function () {
    return this.get('store').findAll('route').then(function(result){
     return result.filterBy('isNew', false);
    });
  }).readOnly(),

Update:

Consider using different names than route or routes for your route name and computed property name.

In route.js

model(){
 return Ember.RSVP.hash({
  newRecord: this.store.createRecord('route', {}),
  routes : this.get('store').findAll('route').then(function(result){
     return result.filterBy('isNew', false);
    }),
  });
},
setupController(controller,model){
 this._super(...arguments);
 controller.set('NewRecordModel',model.newRecord);
 controller.set('routes',model.routes);
}

and in route.hbs template,

{{my-select
    selected=NewRecordModel.takeover
    options=routes
}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

Issue with Multiple File Upload Functionality in Dropzone.js + Laravel (Only allowing one file to be uploaded)

Looking for assistance in uploading multiple files using AJAX with Dropzone.js plugin. This is what I have implemented so far - HTML (view)- <div class="dropzone" id="add-slide-image"> </div> JS- Dropzone.autoDiscover = false; var myDropzo ...

The Chrome (version 58) webdriverio is currently inactive, while Firefox is up and running

Previously, I successfully ran automation tests on Firefox and Chrome locally. However, there seems to be an issue that has arisen when trying to run them on Chrome recently. My system configurations: Operating System: Windows 10 (64-bit) Chrome Versio ...

Steps for setting the value of a textbox within a bootstrap popover

When a user clicks on an Anchor element, I am displaying a Bootstrap popover using the following JQuery code. Jquery $("[data-toggle=popover]").popover({ trigger: 'click', placement: "top", html: true, ...

Ways to avoid browser refresh when uploading files in React applications

I'm working with a simple file upload form in React using hooks. import React, { useState } from 'react'; import { FlexContainer } from '@styles/FlexContainer'; const TestUpload = () => { const [file, setFile] = useState<F ...

What steps can I take to display a download button when a file is clicked on?

As a backend developer, I usually don't delve into JavaScript tasks, but I have a simple query for JavaScript developers that I need help with. Here is my question: I am trying to display a download button when a specific file is clicked using jQuery ...

AngularJS controller containing a nested app

Is there a way to implement this structure using AnglularJS? <body ng-app="mainBodyAppWrapper"> <div ng-controller = "mainBodyController"> <div ng-app="myApp"> <div ng-controller="controller3"> ...

Using ReactJS to send formData to an Express API and retrieving a JSON response

Attempting to have the ReactJS frontend send a username and password from a form to my express API via a proxy, with the intention of having the API return a JSON file containing a user id. While the proxy connection is working as expected, the issue arise ...

Retrieving an HTML element that has been added through DOM manipulation

After successfully creating a Jquery function that inserts a 'save button' into the page when a specific button is clicked, I encountered an issue with another function meant to be activated when the save button is clicked. The first function see ...

Canvas Frustratingly Covers Headline

Several months ago, I successfully created my portfolio. However, upon revisiting the code after six months, I encountered issues with its functionality. Previously, text would display above a canvas using scrollmagic.js, and while the inspector shows that ...

Encountered the error message "Router.js file throwing a TypeError: next is not a function" while implementing navigation guards in my Vue 3 project

I'm puzzled as to why 'i' doesn't recognize the next function, even though I followed a similar video that implemented it without any errors. import Dashboard from "./Pages/Dashboard.vue"; import Customers from "./Pages/Customers.vue"; ...

Utilizing unique background images tailored to different screen resolutions

In order to enhance the user experience on my website, I am looking to implement a feature that dynamically changes the background images based on the user's screen resolution. My plan is to use a small snippet of JavaScript within the <head> s ...

The focus and blur events for the document in a content editable iframe are not activated by Chrome

As I modify the content of an iframe while it is in focus, I have noticed that this seems to function properly in Firefox. However, I am facing issues as the focus and blur events do not seem to trigger in Google Chrome! var iframe = $('#iframe') ...

What could be the reason for the inability of my external jQuery file to be implemented on a className within React

I am currently in the process of building a navigation menu for the mobile version of my website using jQuery. However, I'm encountering an issue when trying to integrate it within the className of my reactjs application. Despite placing the jQuery fi ...

Utilizing the 'input' method to modify the key of an array object within specified elements in a Vue.js application

i am looking to implement an input field that can be used to edit the title of the currently selected element component (the selection is made by clicking). The challenge here is to have a single input that works for each individually selected element. I h ...

Angular routes are failing to update the view even after attempting to refresh

I am facing an issue while trying to develop an angular app where the child state is not loading properly. app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('home& ...

Steps for inserting an additional header in an Angular table

https://i.stack.imgur.com/6JI4p.png I am looking to insert an additional column above the existing ones with a colspan of 4, and it needs to remain fixed like a header column. Here is the code snippet: <div class="example-container mat-elevation-z8"> ...

Selenium webdriver cannot find the element within the JavaScript code

await driver.findElement(By.id('closeBtn')).click(); or await driver.findElement(By.xpath('//*[@id="closeBtn"]')).click(); When attempting to use the above conditions for a pop-up, it does not work as expected. An error is ...

Utilizing Inquiries within Arrays

I've been working on a quiz application and I have successfully built the array with questions and answers. However, I'm facing some challenges in getting the next question to display after clicking the submit button. Here is a snippet of the cod ...

Encountered a failure while loading modules in AngularJS

When I tried opening the index.html page using Chrome, I encountered an error stating that the correct modules could not be found. Uncaught SyntaxError: Unexpected token < angular.js:1 Uncaught SyntaxError: Unexpected token < controller.js:1 ...