I've this configure() function in my form:
public function configure() {
$this->current_user = sfContext::getInstance()->getUser()->getGuardUser();
unset($this['updated_at'], $this['created_at']);
$this->widgetSchema['idempresa'] = new sfWidgetFormInputHidden();
$id_empresa = $this->current_user->getSfGuardUserProfile()->getIdempresa();
$this->setDefault('idempresa', $id_empresa);
$this->widgetSchema['no_emisor'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingEmisor', 'add_empty' => 'Seleccione un Emisor', 'expanded' => false, 'multiple' => false));
$this->validatorSchema['idempresa'] = new sfValidatorPass();
$this->validatorSchema['no_emisor'] = new sfValidatorPass();
}
And I'm need to define a relation data in save() function so I do this:
public function save($con = null) {
$new_machine = parent::save($con);
$relation = new SdrivingMaquinaEmisor();
$relation->setIdmaquina($new_machine);
$relation->setIdemisor();
$relation->save();
return $new_machine;
}
In order the set the Idemisor, how do I access to the selected value when users submit the form? Is this the best way to achieve this?
EDIT
After take the suggestion about how to access no_emisor value now my code looks like:
public function save($con = null) {
$new_machine = parent::save($con);
$relation = new SdrivingMaquinaEmisor();
$relation->setIdmaquina($new_machine);
$relation->setIdemisor($this->values['no_emisor']);
$relation->save();
return $new_machine;
}
But I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'idmaquina' cannot be null
For some reason $new_machine doesn't return the id of the latest saved element. Maybe I'm doing in the wrong way so what I'm doing wrong?
I think you might want to do this in the form's doUpdateObject instead, since that receives the cleaned values.
http://www.symfony-project.org/api/1_4/sfFormObject#method_doupdateobject
Edit:
Alternatively, $this->values['no_emisor'] should work once the form has been bound.
Related
I been trying to change the value of RouteAttr.RoutedForRole if it is equal to
SHead but I checked in run time and the query was not changed even though it went to the foreach loop and there were valid entries. I also tried adding the foreach loop in the view but it didn't change anything.
public ViewResult Index()
{
IQueryable<ServiceRequestViewModel> query;
query = from c in context.ServiceRequests
select new ServiceRequestViewModel
{
ServiceRequestId = c.ServiceRequestId,
ServiceDescription = c.ServiceDescription,
RequestNumber = c.RequestNumber,
Title = c.Title,
RouteAttr = c.RouteAttr,
LogAttr = c.LogAttr
};
foreach (var item in query)
{
if (item.RouteAttr.RoutedForRole == WorkflowRole.SHead)
{
item.RouteAttr.RoutedForRole = WorkflowRole.HRManager;
}
}
return View(query);
}
Below is my gridview.
#Html.Grid(Model).Columns(col =>
{
col.Add(o => o.ServiceRequestId)
.Encoded(false)
.Sanitized(false)
.Filterable(true)
.Titled("SRF No.")
.SetWidth(150)
.RenderValueAs(o => Html.ActionLink(o.RequestNumber, "Details", new { id = o.ServiceRequestId }));
col.Add(o => o.Title)
.Filterable(true)
.SetWidth(400)
.Titled("Title");
col.Add(o => o.LogAttr.CreatedBy)
.Filterable(true)
.Titled("Requestor");
col.Add(o => o.RouteAttr.RoutedForRole)
.Filterable(true)
.Titled("Status");
}).WithPaging(10).Sortable(true)
I've been told in the comments why it's not returning so now I want to know how to update an item in iqueryable and return it in view.
Just like what #Enigmativity said in the comments, I changed the query into an array.
var data = query.ToArray();
He suggested I return data but it didn't work since ServiceRequestViewModel requires an IQueryable type. So I changed it back to IQueryable type so I can return it to view.
var queryable = data.AsQueryable();
Hi I have a business logic layer that returns selectlistitems to a controller, so that will then pass to the view to populate select lists.
I have this method that works:
public IEnumerable<SelectListItem> GetDevices
{
get
{
using (IDeviceData repository = _dataFactory.Create())
{
return repository.DeviceTypes.ToList()
.Where(dt => dt.ParentId == 10 )
.Select(dt =>
new SelectListItem
{
Text = (dt.Name).Trim(),
Value = dt.Id.ToString()
});
}
}
}
And this that doesn't:
public IEnumerable<SelectListItem> GetGroups(int deviceTypeId)
{
using (IDeviceData repository = _dataFactory.Create())
{
return repository.DeviceTypeConfigurationParameterGroupMaps.ToList()
.Where(cm => cm.DeviceTypeId == deviceTypeId)
.Join(repository.ConfigurationParameterGroups, cm => cm.ConfigurationParameterGroupId, cg => cg.Id, (cm, cg) => new { cm, cg })
.Select(cg =>
new SelectListItem
{
Text = (cg.cg.Name).Trim(),
Value = cg.cg.Id.ToString()
});
}
}
The obvious difference is the join between two tables, the error I receieve is:
Results View = The type '<>f__AnonymousType0<p,d>' exists in both 'System.Web.dll' and 'EntityFramework.dll'
This is receieved when trying to expand the results whiel debugging. Any advice would eb welcome as I'm not overly familiar with LINQ
Figured it out:
public IEnumerable<SelectListItem> GetGroupsForDevice(int deviceTypeId)
{
using (IDeviceData repository = _dataFactory.Create())
{
return repository.DeviceTypeConfigurationParameterGroupMaps
.Where(cm => cm.DeviceTypeId == deviceTypeId)
.Join(repository.ConfigurationParameterGroups, cm => cm.ConfigurationParameterGroupId, cg => cg.Id, (cm, cg) => cg )
.ToList()
.Select(cg =>
new SelectListItem
{
Text = (cg.Name).Trim(),
Value = cg.Id.ToString()
}).ToList() ;
}
}
I needed to add ToList() after the join, and then again after converting to SelectlistItem. I also didnt need th create the new anonymous type - Thanks to joanna above for that.
This is the answer but not a good explanation, if anyone wants to pad it out a little please feel free!
I'm creating a table using a EF migration such as:
this.CreateTable("Message",
c => new
{
Id = c.Long(nullable: false, identity: true, defaultValue: 0),
Subject = c.String(nullable: false, maxLength: 64),
Body = c.String(nullable: false, isMaxLength: true)
})
.PrimaryKey(c => c.Id)
.Index(c => c.Id, unique: true);
How can I define the Id field to be auto_increment? I'm pretty sure it has to be possible, but im just struggling to find out...
Thanks.
Ok, it seems that setting the property "identity: true" in field should be enough but for some reason the field is not defined as IDENTITY(1, 1).
Found a workaround in this post:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/33db16ac-e166-455f-a47b-1e5fe0557979/
And it worked for me like this:
Id = new ColumnModel(PrimitiveTypeKind.Int64) { IsNullable = false, IsIdentity = true },
Now its defining the column as IDENTITY(1, 1)
If you do want to automatically generate it in code, you could skip the annotation on the Id field and do something like below.
public abstract class AbstractContext : DbContext {
/// <summary>
/// Custom processing when saving entities in changetracker
/// </summary>
/// <returns></returns>
public override int SaveChanges()
{
// recommended to explicitly set New Guid for appropriate entities
foreach (var entry in ChangeTracker.Entries<ModelBase>().Where(e => e.State == EntityState.Added) ) {
// only generate if property isn't identity...
Type t = entry.Entity.GetType();
var info = t.GetProperty("Id").GetCustomAttributes(
typeof(DatabaseGeneratedAttribute), true).Cast<DatabaseGeneratedAttribute>().Single();
if (info.DatabaseGeneratedOption != DatabaseGeneratedOption.Identity) {
entry.Entity.Id = Guid.NewGuid(); // now we make it
}
}
return base.SaveChanges();
}
}
For more information check Working with Entity Keys
I got this from the link Which I showed above comment.
I hope this will help to you.
I have a method to retrieve session variables, in this case Organizations. For some reason, when I call the get session method the get Organizations and pass the data to a SelectList method to handle some naming logic, the session variable is getting updated. I don't wanted the session values updated and don't understanding what is happening. Below are all the methods. What am I missing?
Controller Method:
public ActionResult Create()
{
SignUpEventFormModel model = new SignUpEventFormModel();
SelectListHelpers listHelper = new SelectListHelpers();
model.OrganizationList = listHelper.GetOrgSelectList(sessionRepository.GetUserSession().Organizations, null);
return View(model);
}
Get User Session Method:
public UserSession GetUserSession()
{
UserSession us = (UserSession)HttpContext.Current.Session["UserSession"];
if (us == null)
{
string email = HttpContext.Current.User.Identity.Name;
SessionSetupRepository sessionsetupRepository = new SessionSetupRepository(new UserRepository(null, null), new SignUpRepository(), new ActivityRepository(), new OrganizationRepository());
us = sessionsetupRepository.SetupUserSession(email);
}
return us;
}
Get Org Select List Method:
public SelectList GetOrgSelectList(IEnumerable<Organization> Orgs, int? SelectedOrgID)
{
List<Organization> OrgList = Orgs.ToList();
OrgList.Where(o => !o.IsAdmin).ToList().ForEach(o => o.Name = o.Name + " (Permission Request Required)");
if (SelectedOrgID.HasValue)
return new SelectList(OrgList, "OrganizationID", "Name", (int)SelectedOrgID);
else
return new SelectList(OrgList, "OrganizationID", "Name");
}
Created a IList parameter and converted the organizations to a list.
I'm trying to set up a multi-select filter on a foreign key in the symfony admin. I think I've set up everything correctly but for some reason it's not working:
public function configure()
{
parent::configure();
$s = Doctrine_Query::create()->
from('Status s')->
execute();
$status_choices = array();
foreach ($s as $key => $value) {
$status_choices[$value->getId()] = $value->getName();
}
$this->widgetSchema['status_id'] = new sfWidgetFormChoice(array('choices' => $status_choices, 'multiple' => true, 'expanded' => true));
$this->validatorSchema['status_id'] = new sfValidatorChoice(array('required' => false, 'choices' => $status_choices, 'multiple' => true));
}
public function getFields()
{
$fields = parent::getFields();
$fields['status_id'] = 'StatusId';
return $fields;
}
public function addStatusIdQuery(Doctrine_Query $query, $field, $values)
{
$fieldName = $this->getFieldName($field);
if (!empty($values))
{
$query->addWhereIn(sprintf('%s.%s', $query->getRootAlias(), $fieldName), $values);
}
}
Any help would be greatly appreciated...
In your validatorSchema, to validate data posted, you have to use array_keys($status_choices)
because values sent after posting the form are keys and not labels.
And the addWhereIn is not a Doctrine_Query method, use andWhereIn or whereIn
Hope that will help you