Ignore optional columns on save - entity-framework

When I update a table from a Form through Autogenerated EF, if I remove some data-columns from the view form because I don't want to be editable, that columns are updated with null value, how can avoid this behavior? I read here: Entity Framework: Ignore Columns removing it from the model, but not always I want to ignore these datacolumns.
thank!

Another approach is to use annotations
[HttpPost]
public virtual ActionResult Edit(
[Bind(Prefix="", Include="field1", Exclude="field2")]MyClass myClass)
{
....

asp.net MVC provide you with UpdateModel method, look on the overload
protected internal void UpdateModel<TModel>(
TModel model,
string prefix,
string[] includeProperties,
string[] excludeProperties
)
where TModel : class
using it you are able to exclude or include particular properties by their names

Related

Thymeleaf form with multiple objects of the same class

Simple problem but can't find a solution: I have a Thymeleaf form used to add a new object, say of a Book class. It works perfectly well and I only need that particular form for adding new objects, not editing the existing ones. The question is: how can I put several objects of the Book class in the same single form? So, purely for convenience, instead of filling form for a single book and clicking Send you can fill form for several books at once and only then click Send, have them all inserted into the database (in whatever order) and also have the option to fill the form partially (e.g. the form has room for 5 books but it will also accept 1, 2, 3 or 4 and you can leave the rest blank).
Edit: I've tried passing a list of object to the Thymeleaf template with the form bound to the whole list and iteration inside, but Thymeleaf throws BingingResultError upon rendering it.
You need to use a wrapper object to realize what you want.
Something like:
public class BooksCreationDto {
private List<Book> books;
// default and parameterized constructor
public void addBook(Book book) {
this.books.add(book);
}
// getter and setter
}
Then you need to pass this object as a model attribute in your controller:
BooksCreationDto booksForm = new BooksCreationDto();
model.addAttribute("form", booksForm);
bind fields using index property
th:field="*{books[__${itemStat.index}__].title}"
and get back the result with
#ModelAttribute BooksCreationDto form
in your controller.
For a complete and detailled explaination visit: https://www.baeldung.com/thymeleaf-list

October CMS - deferred bindings with images that aren't attachments

I'm using the October CMS and I'm having some trouble with deferred bindings.
I have two tables: products and product_images. I've split up my backend form into two tabs, one for product details and one for the product images:
I have my relationships set up correctly and use the following code (placed in a partial) to render the product images list:
<?= $this->relationRender('product_images'); ?>
The images tab looks like this:
The problem happens when I try to create a new image. When saving the image from the image modal, I get this exception:
I understand why there would be a constraint violation: The main record hasn't been saved yet, so there's no id for the image record to reference. In other words, the product image can't be associated with the product because the product doesn't exist yet.
The OctoberCMS documentation on deferred binding hints at a solution. But the documentation also states,
Deferred bindings are supported in the back-end Form behavior
automatically
Indeed, I haven't explicitly written any back-end form processing code. So even if I wanted to follow the instructions on deferred bindings, I wouldn't know where to put it. Any suggestions?
UPDATE:
In my config_relations.yaml file, I've set deferredBinding to true, but it made no difference:
product_images:
label: Image
deferredBinding: true
My products controller looks like:
class Products extends \Backend\Classes\Controller
{
public $implement = [
'Backend.Behaviors.FormController',
'Backend.Behaviors.ListController',
'Backend.Behaviors.RelationController'
];
public $formConfig = 'config_form.yaml';
public $listConfig = 'config_list.yaml';
public $relationConfig = 'config_relation.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('MyPlugin.Products', 'products');
}
public function index()
{
$this->makeLists();
$this->makeView('index');
}
I do not have a product_images controller. I'm not sure why. Is that the issue?
My mistake was that I had put constraints on the product_id column in the product_images table:
$table->integer('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('me_myplugin_products');
Apparently I need to allow that column to be null. Changing it to this worked:
$table->integer('product_id')->nullable();

What alternatives are there to Yii active form?

I wish to build a form that does not create/update any active records. An example of such a form would be a search filter using check boxes for the user to select which categories to apply to the search.
Everything I read about forms in Yii is centred around the CActiveForm class. What is the Yii way to build forms that don't use active records?
If you want to embrace Yii's convenient form handling, you should use CActiveForm. It does not require CActiveRecord. But it always requires a model for your form data - which is a good thing, because this will keep the validation rules out of your view files. Instead of a CActiveRecord you could also build a simple model class from CFormModel.
class SomeForm extends CFormModel
{
public $name;
public $email;
public function rules()
{
return array(
array('name,email','required'),
array('email','email'),
);
}
}
Check the docs of the CHtml class. While it contains all the active* method, there are plain form methods in there as well, such as checkBox() or checkBoxList() that sound like what you're looking for.

GWT Templates & GXT Xtemplates - how to sanitize display fields

I'm just getting into using #Template and #XTemmplate within my code.
I'm always concerned about user originated content vs trusted content.
This is the sample from GWT SafeHtml
public interface MyTemplates extends SafeHtmlTemplates {
#Template("<span class=\"{3}\">{0}: {2}</span>")
SafeHtml messageWithLink(SafeHtml message, String url, String linkText,
String style);
}
This is the sample from the GXT XTemplate doc
public interface SampleXTemplates extends XTemplates {
#XTemplate("<div>Hello, {name}!</div>")
SafeHtml hello(String name);
}
In either, is there a way in the template to declare a display field to be sanitized or trusted?
Something ala HtmlSanitizer
All String values rendered in an XTemplate/SafeHtmlTemplates are automatically sanitized - try passing in <, >, or & characters. This is true whether they are passed in to an attribute or the space between tags. If GWT cannot enure the safety of such a string (such as passing it into the href attribute of the a tag, or into a style attribute), it will emit a warning. Your first example is likely to get such a warning.
SafeHtml instances can be passed in to declare 'I know that this string is safe'. Typically, you create those using SafeHtmlUtils, a SafeHtmlBuilder instance, or another template of some kind.
Safe urls can be SafeUri instances - create them with UriUtils. This will get around the possible warning in your first example.
Safe styles can be SafeStyles instances - create them using SafeStylesBuilder instances or static methods in the SafeStylesUtils class.
And finally, as an implementation detail, XTemplates are generated by parsing out the logic and the named parameters and getters, and turned into SafeHtmlTemplates before generated into JavaScript. This ensures that anything that SafeHtmlTemplates will make safe will also be safe in XTemplates.

Get value from Entity Framework for Dropdown List and Return selected value in MVC

Assuming i got a table called Countries and using Entity Framework, i want to know how could i populate the available countries (listed in the table countries) to view as drop down list and return the value to HTTPPost Controller
i got
public ActionResult SignUp()
i think the populate code should be here but i not sure
how to retrieve from entity framework and populate into view
and
[httpPost]
public ActionResult SignUp()
i want to read the user selected value and i think is
int value = form["DropDownListName"].SelectedIndex + 1;
can anyone please guide me on this with some hint or example , please ? Thx a lot =D
To be honest, you're not really working in an MVC pattern here. Don't put UI construction logic in your constructor.
Rather, expose the ID that you want to bind to the list via a model that you pass to a View() method in your constructor.
In your view, use the name of that property as the Name of a Drop-down and create a helper class to generate the list of values.
I'd give you a more specific example, but I'm in the cinema with my iPad, so a bit stuck for access to Visual Studio at the moment!