How do I populate Doctrine fields from PHP to complement form data? - symfony1

I have a form which sends data from the server, which works just fine in Symfony, but what I don't know, is how can I set some fields by myself, like the user_id field, which I clearly don't want the user to send, I want to add the value for that just before Doctrine validates it.
Any relevant documentation links would be also greatly appreciated.

Unset your fields in configure method:
class YourForm extends BaseYourForm
{
public function configure()
{
unset($this['user_id']);
}
}
Override save method of Your model:
class Your extends BaseYour
{
public function save(Doctrine_Connection $conn = null)
{
$this->setUserId($whatever);
parent::save($conn);
}
}

Related

unable to Validate Custom components in SmartGWT

I am unable to get my custom compoenent to be validated in the dynamic form. I tried many versions but it is not working as expected. For e.g. either the label is not showing in BOLD to indicate the field is mandatory and it aloows to save the form without entering anything in the field. Only when the user enters something in the field and deletes it, then the red icon is displayed to the user that the field is mandatory.I dont know what i am missing. please help. code is below
telnumber = new CustomTelephoneTextItem();
telnumber.setName("tel");
telnumber.setTitle("Tel");
telnumber.setTitle(nerpweb.clientFactory.getMessages().tel());
Below is my Custom TextItem which i am using in the above class
public class CustomTelephoneTextItem extends CanvasItem
{
textField_value = new CustomIntegerItem();
textField_value.setShowTitle(false);
textField_value.setWidth(100);
textField_value.setRequired(true);
form.setItems(textField_value, textField_code);
form.validate();
setWrapTitle(false);
this.setCanvas(form);
First, if you want to item title showin bold, you must call item's setRequired(true).
in your code is telnumber.setRequired(true);
Second, if you want to validate item on form.validate(), you must override validate() function in your item and write validation code in this function.
in your code is call form.validate() in CustomTelephoneTextItem validate() function
Here is the code to be implemented to validate custom component
This code will go in your Custom component which you will implement
#Override
public Object getValue()
{
if (validate() && textField_value.getValue() != null)
return textField_value.getValue();
return null;
}
#Override
public void setRequired(Boolean required) {
super.setRequired(true);
}
#Override
public Boolean validate() {
return super.validate();
}
#Override
public void setValidators(Validator... validators) {
textField_value.setValidators(validators);
}
Then in the class where you will create the custom component you will call the setRequired() method,like so
telnumber.setRequired(true);

Selected attributes of genemu_jqueryselect2_entity not stored to database

I'm using genemu_jqueryselect2_entity for a multiple selection field within a form (located in an Sonata admin class) for a so called Uni (university) entity:
->add('courses', 'genemu_jqueryselect2_entity',array('multiple' => true, 'class' => 'PROJECT\UniBundle\Entity\Course'))
But the selected entries are not filled into my entity. With firebug I was able to detect, that the ids of the courses are passed correctly via POST.
Maybe the field is not correctly mapped to the Uni entity, but I have no idea why.
This is the adding method of my Uni entity, which doesn't even get called:
public function addCourse(\PROJECT\UniBundle\Entity\Course $courses)
{
$this->courses[] = $courses;
return $this;
}
How can I get the field to be mapped with the courses attribute of Uni? How could I debug this?
Any help will be appriciated!
Try writing that method like this:
public function addCourse(\PROJECT\UniBundle\Entity\Course $course)
{
$this->courses[] = $course;
$course->setUniversity($this); // Or similar.
return $this;
}
Otherwise foreign key is not set on a course row in the DB.
Try to create method setCourses
public function setCourses(\Doctrine\Common\Collections\Collection $courses)
{
$this->courses = $courses;
...
I don't know why, but the method addCourse isn't called.
Anyway, Tautrimas Pajarskas's answer was usefull to me so I gave an upvote.
The foreign key relationship was the necessary and missing part of my code.
I implemented it in the university sonata admin like this:
private function addUniToCourses ($university) {
foreach($university->getCourses() as $course) {
if(!$course->getUniversities()->contains($university)) {
$course->addUniversity($university);
}
}
}
public function prePersist($university) {
$this->addUniToCourses($university);
}
public function preUpdate($university) {
$this->addUniToCourses($university);
}
This was the solution to my problem.
I had the same problem a while ago: Symfony2, $form->bind() not calling adder methods of entity
Solution:
For the adder (addCourse()) to be called, you have to disable the by_reference option of the field:
->add('courses', 'genemu_jqueryselect2_entity',
array(
'by_reference' => false, // This line should do the trick
'multiple' => true,
'class' => 'PROJECT\UniBundle\Entity\Course'))

ASP MVC 4 Using a class to validate a get/set within a model

working on a project right now and I'm relatively new to MVC, I have a model which looks something like
public class MyViewModel
{
public string check1 {get;set;}
public string check2 {get;set;}
}
I also have a class which I want to use to validate these checks using a custom regex, such as
public class WebCommon
{
public static bool Validation(string validate)
{
bool validatestatus = false;
Regex check = new Regex(my regex here);
if (check.IsMatch(validate))
{
validatestatus = true;
return validatestatus;
}
else
{
return validationstatus;
}
}
}
Basically what I'd like to do is call that method inside the webcommon class, inside the model itself to check when I take in the values for the get;sets in my model, and if it returns false, then I want it to throw an error within the view saying that it is not a valid input. Thanks!
This question here is about making custom regular expression attrbutes and should answer your question.
Check out either Regular Expression Attribute
Or implement and IValidatableObject

Database fields that automatically update on creation or on update with symfony

For example (it is a bad example for the purpose of my question), i want to store the user fullname by concatenating the firstname and lastname.
I have a table user with firstname, lastname, fullname
Is there a way to create a field in the schema with a trigger function that stores in fullname firstname+lastname ? The same way the created_at works (with timestampable)
I use doctrine and symfony 1.4
You definately don't need to create a behaviour for something as simple and as unreusable as this.
Just override your model save method:
class Model extends BaseModel
{
public function save(Doctrine_Connection $conn)
{
$this->fullname = sprintf ('%s %s', $this->firstname, $this->lastname);
return parent::save($conn);
}
}
Dziamid has already directly answered what you asked. But consider also whether you really need to store such duplicate data. A different solution which I use is this:
class Model extends BaseModel
{
public function getFullName() {
return ($this->name_first . ' ' . $this->name_last);
}
public function getFullNameLastFirst() {
return ($this->name_last . ', ' . $this->name_first);
}
}

Passing values from action class to model class in symfony

I have a action class for saving some data to a database.In action class iam getting a id through url.I have to save the id in table.
I am getting the id by $request->getParameter('id')
I used this code for saving
$this->form->bind($request->getParameter('question_answers'));
if ($this->form->isValid())
{
$this->form->save();
$this->redirect('#homepage');
}
in model class i used a override save method to save extra field
public function save(Doctrine_Connection $conn = null)
{
if ($this->isNew())
{
$now=date('Y-m-d H:i:s', time());
$this->setPostedAt($now);
}
return parent::save($conn);
so i want to get the id value here .
So how can i pass id value from action class to model class
is any-other way to save the id in action class itself
Thanks in advance
Just use
$this->form->getObject()->setQuestionId($request->getParameter('id'));
$this->form->save();
QuestionId=field name
$request->getParameter('id')= is the default value
Most probably not the best solution but you can save that id value in a session variable and use it later anywhere you need. something like:
$this->getUser()->setAttribute('id', $request->getParameter('id')); // in action class
and
sfContext::getInstance()->getUser()->getAttribute('id'); // in model class
If your model has a field for this ID already (eg in your example posted_id), then you can do one of 2 things:
1: Pass the ID to your form when you create it, as an option:
$this->form = new MyForm(array(), array("posted_id" => $id));
and then you can override your form's doSave() method to set the field:
// ...
$this->getObject()->posted_id = $this->getOption("posted_id");
// ...
or similar
2: Add a widget to your form in the configure() method with a corresponding validator, and pass in the ID when you get the values from the request:
$values = $request->getParameter('question_answers');
$values["posted_id"] = $request->getParameter("id");
$this->form->bind($values);
If you're rendering your form manually, just don't render this new field in your view template.
Either way, saving the model as a result of the form saving it will include this new field I believe. The second one is from memory, but it should technically work... :-)
Best practice I'm using consists of 2 steps:
Pass additional data to forms' options (2nd constructor's parameter or just $form->setOption('name', 'value'));
override protected method doUpdateObject in way like this:
protected function doUpdateObject($values)
{
$this->getObject()->setFoo($this->getOption('foo'));
parent::doUpdateObject($values);
}
Enjoy!
You could use (sfUser)->setFlash and (sfUser)->getFlash instead of setAttribute, it's more secure...

Resources