How to dynamically set the <% = %> in MVC Razor - razor

I need to dynamic add a key field name in my razor code.
I just am not sure how to set it up properly so data.KeyNameField is set at run time
I tried string.format in my razor, but I do not think it will work because the <% %> is important to set the key field on the client
.CellTemplate(
#<text>
#Model.OpenRecord.OpenRecordButtonText
</text>);
}
To dynamically be able to pass my key field name in so I can add the unique id onto my URL.
I need to replace .'THE_GUID' with my property on my model of the key field name

Answer:
if (Model.HasOpenRecordButton && Model.OpenRecord != null)
{
string urlAction = Url.Action(Model.OpenRecord.OpenRecordButtonAction, Model.OpenRecord.OpenRecordButtonController);
string rawUrl = string.Format("{0}?id=<%= data.{1} %>", urlAction, Model.KeyFieldName);
column
.Add()
.VisibleIndex(Model.OpenRecord.ColumnPositionIndex)
.Caption(Model.OpenRecord.Caption)
.DataType(GridColumnDataType.String)
.Width(Model.OpenRecord.ColumnWidth)
.CellTemplate(
#<text>
#Model.OpenRecord.OpenRecordButtonText
</text>
);
}
Where data.{1} will be the key field name and will BIND the value of that field as being id=*

Related

how to get model primary key value after save

i have a problem when i try to get the primary key (auto increment) from the db after i save the model.
In the database the tabel doesn't have a primary key so i set it using this:
public static function primaryKey(){
return ['id_cod'];
}
And i removed it from the models rules.
When i save the model, all the data is saved on the db included id_cod, but if i try to access to this property it gives me null.
$evento = new Evento();
//populate the model with some data
//..... eg: $evento->name = 'name';
//save model
$evento->save();
$evento->refresh();
echo Yii::$app->db->getLastInsertID(); // gives me the correct id_cod but i think it's not the correct way
echo $evento->id_cod;//gives me null
echo $evento->name;//gives me name
How can i get the id_cod just after save the model?

mySQL - Unicity constraint depending on other column

I have a table item whose columns are id type code image
Type column
type is a enum and could be text or logo.
Possible situations
If type === 'text' then image is null
If type === 'logo' then code is null
What I would like
If type === 'text' then the unicity is defined by code
If type === 'logo' then the unicity is defined by image
Questions
How can I write this unique constraint in mySQL ? In a migration with laravel ?
I don't think you can declare a unique constraint in that way. You could simplify your table though, by keeping your type column but using a single field for the purpose of either code or logo. You could call this field value for example. Then you could add a unique constraint to type and value like this:
Schema::create('items', function (Blueprint $table) {
// Your fields here...
$table->unique(['type', 'value']);
});
For convenience you could always add accessors in your model to access code or image as if they were fields, for example:
class Item extends Model
{
public function getCodeAttribute()
{
return $this->type === 'text' ? $this->value : null;
}
public function getImageAttribute()
{
return $this->type === 'logo' ? $this->value : null;
}
}
That will allow you to access code and image as if they were fields and your model will return either the value or null based on the type of your Item.
$text = new Item(['type' => 'text', 'value' => 'Hello World!']);
echo $text->code; // Hello World!
echo $text->image; // null
$logo = new Item(['type' => 'logo', 'value' => 'your-image.jpg']);
echo $text->code; // null
echo $text->image; // your-image.jpg
create code and image column in migration table with default value as null, then if you don't set a value to a column, its value be null automaticaly
$table->enum('type', ['image', 'code']);
$table->string('image')->default(null);
$table->string('code')->default(null);

Laravel 5.4 save NULL to database not working

The following code results in an empty value inside the database and when I get it out of the database its an empty String.
$customer->update(['company' => NULL]);
You should consider 3 things:
1) Make sure company column in nullable in your table. If it's not it won't be possible to put null in there.
2) Make sure you have in $fillable property of Customer model column company
3) Verify you don't have any mutator in your Customer model - so verify you don't have setCompanyAttribute method that might change value automatically to empty string if it's set to null
SOLUTION
If you want a field inside the database to be null and you do not use a mutator everything is fine.
Are you using a mutator, in my case the following snippet.
public function setCompanyAttribute($value)
{
$this->attributes['company'] = ucfirst($value);
}
Then you need to check if $value is null and then set it manually to null otherwise it will be an empty string.
To do that automatically on every model you can set the empty string back to null inside your EventServiceProvider.
Event::listen('eloquent.saving: *', function ($eventName, array $data) {
$attributes = [];
foreach ($data as $model) {
foreach( $model->getAttributes() as $key => $value ) {
$attributes[$key] = (is_string($value) && $value === '') ? null : $value;
}
$model->setRawAttributes($attributes);
}
return true;
});
It's important to first check all attributes from the model and set it to a temporary array. Now inside the setAttribute() method on the model instance the checks are done if a mutator exists. But thats exactly what you do not want, because it would set all fields with a definied mutator to an empty sting. Instead use setRawAttribute so the old attributes are overwritten with the ones from the temporary array.
This is safe to do because if the checked value isn't an empty string the already existing value is taken for that field. Otherwise if it's an empty string then null is set.
Hope it helps!

How to get the value of selectlist in view into controller with or without Json

I can get the value of a dropdownlist this way but i cant get the value of a selectlist item with this code. What i can do to get the value into my controller for my create action.
My Controller Contains :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product products, Design designs, Material materials, Color colors, Picture pictures, FormCollection form,EventArgs e)
{
if (Request.Files != null)
{
long prod = Convert.ToInt64(form["Product"]);
pictures.product_id = db.Products.Single(x => x.id == prod).id;
My View Contains :
#Html.DropDownList("Product", new SelectList((System.Collections.IEnumerable)ViewData["Productlist"], "id", "name"), "Please Select Product", new { onchange = "productlist()", style = "width:190px; padding:4px; margin:4px;" })
i can get dropdownlist value but cant get the value of selectlist..
My View Contains : (SelectList)
<select id="Color" style=" width:190px; padding:4px; margin:4px;" onchange="colorlist()">
<option label="Please Select Color" ></option>
</select>
so if im gonna need to use json how can i use it inside create action and in view.
If you want to use the default binding, then you need an argument in your Create action named "Product" of whatever type you are passing (i.e. string). Then when the form POSTs to the action the binder will set that argument value to the option selected at the time of POST.

Problem with DataMapper, Integer property

I have the following class in my sinatra app (app.rb)
class Project
include DataMapper::Resource
property :id, Serial
property :creatorid, Integer, :key => false
property :name, String
end
Project.auto_migrate! unless Project.storage_exists?
and in the post method, I have:
project = Project.create
project.creatorid = GetLoggedInUserId() #returns an int
project.name = params['projectname']
But when I'm getting the following error:
no such column: creatorid (on the project.creatorid... line)
Suggestions?
You coult try with new method instead that create since latter one is used to generate and save an item on the go while the former one is used to generate an empty item that can be then filled (like you do) and then saved with project.save().
Take a look at documentation here..