Building a simple to-do list app with SwiftUI - date formatting - core-data

I’m playing about with SwiftUI for the first time with a simple to do style app. It has 2 views, one a list view, and the other an Add To Do view, which saves info into core data. In core data I have an entity called ToDo with 2 attributes - title (String) and completion (Date).
In the list view I would like to show the entry - the title and completion date on the same line. I thought I would use string interpolation to do this but run into this error:
Cannot convert value of type 'String' to expected argument type 'Date’.
The code I am using is this:
Text ("\(listedToDo.title!) needs completing by \(listedToDo.completion!)”)
I’ve not really worked with DatePickers and DateFormatters before but it may be how I’m saving the date into core data on the Add Item View?
On that file I added the following variable to your code:
#state var toDoCompletion = Date()
I added this DatePicker to the view:
DatePicker(“Completion date:", selection: $toDoCompletion, displayedComponents: .date)
And the save code:
let newToDoCompletion = ToDo(context: viewContext)
newToDoCompletion.completion = toDoCompletion
How can I finish this last bit on the list view?

Related

How to change the value of a certain core data across VCs/ How to know the index of a created CoreData?

I start from a TableView to create and store user information. This is how I create a core data entity called "Trials" in CreateTrialViewController. And I can successfully fetch it in the tableViewController after I come back to it.
let trial : Trials = NSEntityDescription.insertNewObjectForEntityForName("Trials", inManagedObjectContext: self.managedObjectContext!) as? Trials
{
trial.project = theProject.text
trial.record = theRecord.text
trial.notes = theNotes.text
trial.percentile = ""
managedObjectContext?.save(nil)
}
'
But after I create the Trial, I will get some calculated results from the accelerometer in the next measureViewController, and I want to save the result into 'trial.percentile'.
I have already converted the results into a string, so I can write it directly into the core data attribute. But how can I know the index of this core data that I just created? Should I try to use 'segue' to transmit?
In the tableView it fetches in a ascending sequence of date, so the index is clear. But here in the following VC how to know the index? I still couldn't figure this out by myself... The sequence of my VCs is: TableViewController -> CreateTrialViewController -> MeasureViewController -> TableViewController (start again)
Your table view controller can keep a reference to the newly created object. Insert the object (trial) in the original view controller and pass it on to the next controller in prepareForSegue. So the CreateTrialViewController starts out with a blank object to which the table view controller has a reference.
You configure the object, go to the measure controller, modify the object. When done, you pop these two controllers from the navigation stack and are back in your original table view controller.
Because your table view controller has the NSFetchedResultsControllerDelegate enabled, it will update itself to reflect the data of your new object. Remember, you still have a reference to this object, so you can just use indexPathForObject to retrieve its index path.

Can't set Orchard field values unless item already created

I seem to be having a problem with assigning values to fields of a content item with a custom content part and the values not persisting.
I have to create the content item (OrchardServices.ContentManager.Create) first before calling the following code which modifies a field value:
var fields = contentItem.As<MyPart>().Fields;
var imageField = fields.FirstOrDefault(o => o.Name.Equals("Image"));
if (imageField != null)
{
((MediaLibraryPickerField)imageField).Ids = new int[] { imageId };
}
The above code works perfectly when against an item that already exists, but the imageId value is lost if this is done before creating it.
Please note, this is not exclusive to MediaLibraryPickerFields.
I noticed that other people have reported this aswell:
https://orchard.codeplex.com/workitem/18412
Is it simply the case that an item must be created prior to amending it's value field?
This would be a shame, as I'm assigning this fields as part of a large import process and would inhibit performance to create it and then modify the item only to update it again.
As the comments on this issue explain, you do need to call Create. I'm not sure I understand why you think that is an issue however.

How to assign a value to an Orchard ContentPickerField from code?

I am working on an Orchard site that needs to be able to use some customized forms to create new content items.
To handle this I'm using a controller to display a form and then trying to create the new content items on post back by populating the dynamic items and then sending them through the ContentManagerService's Create() function.
This is working ok until I got to the content picker field I have as part of my content item.
In my project I have a content type of Question Record that has a SubmittedBy field that is a Content Picker Field.
Here is what I can see in the immediate window while processing the post back:
> dynamic q = _questionService.NewQuestion("Why doesn't this work?");
{Custom.Website.Models.Question}
base {Orchard.ContentManagement.ContentPart}: {Custom.Website.Models.Question}
IsNew: true
OriginalQuestion: "Why doesn't this work?"
Summary: null
> q.QuestionRecord
{Orchard.ContentManagement.ContentPart}
base {System.Dynamic.DynamicObject}: {Orchard.ContentManagement.ContentPart}
ContentItem: {Orchard.ContentManagement.ContentItem}
Fields: Count = 5
Id: 0
PartDefinition: {Orchard.ContentManagement.MetaData.Models.ContentPartDefinition}
Settings: Count = 0
TypeDefinition: {Orchard.ContentManagement.MetaData.Models.ContentTypeDefinition}
TypePartDefinition: {Orchard.ContentManagement.MetaData.Models.ContentTypePartDefinition}
Zones: {Orchard.UI.ZoneCollection}
> q.QuestionRecord.SubmittedBy
{Orchard.ContentPicker.Fields.ContentPickerField}
base {Orchard.ContentManagement.ContentField}: {Orchard.ContentPicker.Fields.ContentPickerField}
ContentItems: null
Ids: {int[0]}
The ContentItems property is read-only and the Ids when assigning a new int[] to the Ids array I get a System.ObjectDisposedException with the message: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
Are there any workarounds to get this value set in code or do I need to create my own property to store the related content item ids? It would be very helpful to have the admin interface of the ContentPickerField also available.
Thanks.
If you have a reference to the ContentPickerField, you can assign it a value using the Ids property.
In example (assuming your content type has a part called Question which has a field called SubmittedBy):
var submittedByField = ((dynamic)q.ContentItem).Question.SubmittedBy;
sbmittedByField.Ids = new[] { submittedById };
As Bertrand mentioned, the format to access a content field is: contentItem.PartName.FieldName.
If you attached a field to a type directly via the admin, the part name has the same name as the type name, hence contentItem.TypeName.FieldName (where TypeName is actually the name of the implicitly created part).

How to create a LWUIT List screen in j2me?

i want to create a lwuit list screeen ,the list items are coming to my method from Rss Feed in a loop continuosly,but i am able to append 1 title from rss feed and able to display on device,after that 2,3,4,etcc...items are changing ,but finally,i am able to display 1 title and last title only,here is my code:
//method called by the parsing thread
public void addNews(News newsItem,Vector news) {
String newsArray[]={newsItem.getTitle()};
myNewsList = new List(newsArray);
System.out.println(newsItem.getTitle());//Here i am able to display,second title after that,it is not appending adding to myNewsList
//myNewsList.addItem(newsItem.getTitle());
form1.addComponent(myNewsList);
form1.show();
}
Can you help?
You need to read up about using Lists and the model in LWUIT. When using addItem you should invoke it from the EDT using LWUIT's callSerially method.
Regardless, calling addItem one by one is VERY slow. You should use a model to represent your data, see the makeover demo.

Binding an edit box within a custom control to a form field programatically

I have a notes form with a series of fields such as city_1, city_2, city_3 etc.
I have an XPage and on that XPage I have a repeat.
The repeat is based on an array with ten values 1 - 10
var repArray = new Array() ;
for (var i=1;i<=10;i++) {
repArray.push(i) ;
}
return(repArray) ;
Within the repeat I have a custom control which is used to surface the fields city_1 through city_10
The repeat has a custom property docdatasource which is passed in
It also has a string custom property called cityFieldName which is computed using the repeat
collection name so that in the first repeat row it is city_1 and in the second it is city_2 etc..
The editable text field on the custom control is bound using the EL formula
compositeData.docdatasource[compositeData.cityFieldName]
This works fine but each time I add new fields I have to remember to create a new custom property and then a reference to it on the parent page.
I would like to be able to simply compute the data binding such as
compositeData.docdatasource['city_' + indexvar]
where indexvar is a variable representing the current row number.
Is this possible ? I have read that you cannot use '+' in Expression Language.
First: you wouldn't need an array for a counter. Just 10 would do (the number) - repeats 10 times too. But you could build an array of arrays:
var repArray = [];
for (var i=1;i<=10;i++) {
repArray.push(["city","street","zip","country","planet"]) ;
}
return repArray;
then you should be able to use
#{datasource.indexvar[0]}
to bind city,
#{datasource.indexvar[1]}
to bind street. etc.
Carries a little the danger of messing with the sequence of the array, if that's a concern you would need to dig deeper in using an Object here.
compute to javascript and use something like
var viewnam = "#{" + (compositeData.searchVar )+ "}"
return viewnam
make sure this is computed on page load in the custom control
I was never able to do the addition within EL but I have been very successful with simply computing the field names outside the custom control and then passing those values into the custom control.
I can send you some working code if you wish from a presentation I gave.

Resources