Theres the action
public function actionEfetuarPedidoReserva($idQuarto){
$modelPedidoReservaQuarto = new PedidoReservaQuarto();
$modelPedidoReserva = new PedidoReserva();
$model = new ComodidadesExtra();
$modelListaComodidades = new ListaComodidadesQuarto();
$modelPedidoReservaQuarto->quartoId = $idQuarto;
if($modelPedidoReservaQuarto->save()){
$modelPedidoReserva->nPessoas = 2;
$modelPedidoReserva->preco = 70.00;
$modelPedidoReserva->reservaQuartoId = $modelPedidoReservaQuarto->id;
$modelPedidoReserva->userInfoId = Yii::$app->user->id;
if($modelPedidoReserva->save()){
$model->pedidoReservaId = $modelPedidoReserva->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['efetuar-pedido-reserva', 'idQuarto' => $idQuarto]);
}
return $this->render('../comodidades-extra/create', [
'model' => $model, 'modelLista' => $modelListaComodidades
]);
}
}
}
When i refresh page, it add the last pedidoreservaid inserted + 1;
i Would like to know if am i doing it the right way.
Your problem is that you create new instance of ComodidadesExtra each time when you call $model = new ComodidadesExtra();. Yii2 consider it as new independent row and you need to tell Yii2 that you should take existing row instead, using:
$model = ComodidadesExtra::find()
->where(['pedidoReservaId' => $modelPedidoReserva->id])
->one();
And your controller should look like:
if($modelPedidoReserva->save()){
if(null===($model = ComodidadesExtra::find()->where(['pedidoReservaId' => $modelPedidoReserva->id])
->one())) {
$model = new ComodidadesExtra();
}
$model->pedidoReservaId = $modelPedidoReserva->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['efetuar-pedido-reserva', 'idQuarto' => $idQuarto]);
}
return $this->render('../comodidades-extra/create', [
'model' => $model, 'modelLista' => $modelListaComodidades
]);
}
Related
In my Ticket.php when I create something from CRUD, I want it to get the current time in the Timezone. But I'm getting an error "Object of class DateTime could not be converted to string" I've used TIMESTAMP in my db time_start
I've done this so far:
public function actionCreate()
{
$model = new Ticket();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
} else {
// $employeeIDs = ArrayHelper::map(Employee::find()->all(), 'id', 'emp_name');
$my_date = new \DateTime("now", new \DateTimeZone('Asia/Manila'));
$model->time_start = $my_date;
$model->status = ('On Going');
// $model->employee_respond_id = array_rand($employeeIDs);
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
You should format $my_date when assigning to $model->time_start, because in this way you are assigning a DateTime Object to a primitive member. For example:
$model->time_start = $my_date->format('Y-m-d H:i:s');
I just learned how to create a complex form using multiple models.
public function actionCreate()
{
$model = new Company();
$contact = new Contact();
$address = new Address();
$company_contact = new CompanyContact();
$company_address = new CompanyAddress();
if ($model->load(Yii::$app->request->post()) && $contact->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post())) {
$model->save();
$address->save();
$contact->save();
// we need to insert the index from each key to the table Company_Contact to associate them
$company_contact->id_company = $model->id_company;
$company_contact->id_contact = $contact->id_contact;
// same procedure for Company_Address
$company_address->id_company = $model->id_company;
$company_address->id_address = $address->id_address;
$company_address->save();
$company_contact->save();
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
'contact' => $contact,
'address' => $address
]);
}
}
The problem now is that I don't know how to call back every table data so i can populate my form and afterwards save the changes. I had the idea of using JOIN, but I don't have necessery knoledge to make this work on yii2 framework.
First of all, you need to make sure the methods declaring the relationship Company has to both Contact and Address are correct.
public function getContact() {
return $this->hasOne(Contact::className(), ['id_contact' => 'id_contact'])
->viaTable('Company_Contact', ['id_company' => 'id_company']);
}
public function getAddress() {
return $this->hasOne(Address::className(), ['id_address' => 'id_address'])
->viaTable('Company_Address', ['id_company' => 'id_company']);
}
Now that we know our relationships are correct, we can make some modifications to actionCreate() inside our controller:
public function actionCreate() {
$model = new Company();
$contact = new Contact();
$address = new Address();
// Check if the request was made using post, otherwise skip and render 'create' view
if(Yii::$app->request->isPost) {
// Begin a transaction, so we only make changes to the Database when we can save all the needed records.
$transaction = Company::getDb()->beginTransaction();
try {
$post = Yii::$app->request->post();
// We try to load $model, $contact and $address. If we can't then we throw an Exception that will be caught.
if(!($model->load(Yii::$app->request->post()) && $contact->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post()))) {
throw new \Exception('Could not load post data to models');
}
// Now we try to save them, each by itself. If any of them fail to save then we throw an Exception.
if(!$model->save()) {
throw new \Exception('Could not save $model');
}
if(!$address->save()) {
throw new \Exception('Could not save $address');
}
if(!$contact->save()) {
throw new \Exception('Could not save $contact');
}
// Now we populate the relationships.
// First parametter is the name of the relationship, Second is the model we want to link to.
$model->link('address', $address);
$model->link('contact', $contact);
// With the relationships correctly declared, we don't need to populate the juncture table ourselves, just link both models.
// If the 'link' method cannot link the models, then it will throw an Exception that will be caught.
// If we managed to save all the records and link them, now we commit the transaction so the changes made in the database are not reverted.
$transaction->commit();
return $this->redirect(['index']);
}
catch(\Exception $e) {
// If there are any problems then we will do a rollBack to the transaction, reverting the changes made during the transaction.
$transaction->rollBack();
}
}
return $this->render('create', [
'model' => $model,
'contact' => $contact,
'address' => $address,
]);
}
And now for actionUpdate we just need to get $id which will be used as PK to search for the Company.
public function actionUpdate(&id) {
$model = Company::findOne($id);
// If $model is null, then throw a NotFoundHttpException.
if($model === null) {
throw new \yii\web\NotFoundHttpException('The requested page does not exist.');
}
// We can get the $contact and $address models by using the relationships we already declared.
$contact = $model->contact;
$address = $model->address;
// Now we don't need to change much from actionCreate,
// except we don't need to link $model with $contact or $address because they are already linked,
// we just need to save changes made to them.
if(Yii::$app->request->isPost) {
$transaction = Company::getDb()->beginTransaction();
try {
$post = Yii::$app->request->post();
if(!($model->load(Yii::$app->request->post()) && $contact->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post()))) {
throw new \Exception('Could not load post data to models');
}
if(!$model->save()) {
throw new \Exception('Could not save $model');
}
if(!$address->save()) {
throw new \Exception('Could not save $address');
}
if(!$contact->save()) {
throw new \Exception('Could not save $contact');
}
$transaction->commit();
return $this->redirect(['index']);
}
catch(\Exception $e) {
$transaction->rollBack();
}
}
return $this->render('update', [
'model' => $model,
'contact' => $contact,
'address' => $address,
]);
}
I'm using two models in one controller. one of them is database model (model) another model is for sending sms (smsModel).
I have problem in smsModel.
I got this error in my result:
Class 'fcadmin\models\SoapClient' not found
How can I fix it?
My controller:
public function actionCreate($id) {
$model = new Requestresult();
$smsModel = new SmsSender();
$request_model = Request::findOne(['id' => $id]);
$model->CodeKargah = $request_model->CodeKargah;
$model->month = $request_model->month;
$model->trackingCode = $request_model->trackingCode;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$smsModel->sendSms('09193452126', 'sdf');
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
smsModel:
public function sendSms($to, $text) {
$options = [
'login' => 'myusername',
'password' => 'mypassword'
];
$client = new SoapClient('http://sms.hostiran.net/webservice/?WSDL', $options);
$messageId = $client->send($to, $text);
sleep(3);
return ($client->deliveryStatus($messageId));
}
You need to read up about namespaces. If you're in a namespace and don't tell PHP that you want to use the global namespace, it will look for classes of name x in the current namespace.
In your case you need to be using new \SoapClient.
I am using yii2 for a weigh bridge project
Upon create, the user is redirected to view but my controller doesn't validate the information in such a way that even if data is not entered in the form fields a user is always redirected to view.
How can I implement the validation property
Controller code:
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) ) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
try this
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
for more on validation validation
I am new in zf2. I make a create action and want to get last inserted id but calender_id always equal to zero. How can I get the last insert id in create action ?
Here is my code:
public function createAction()
{
if ($this->zfcUserAuthentication()->hasIdentity())
{
$form = new CalendarForm();
$form->get('user_id')->setValue($this->zfcUserAuthentication()->getIdentity()->getId());
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$calendar = new Calendar();
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$calendar->exchangeArray($form->getData());
$this->getCalendarTable()->saveCalendar($calendar);
if($request->isXmlHttpRequest()) {
//$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
//$calender = new \Calendar\Model\Calendar($dm);
$response = new Response();
$calender_id = $calendar->calendar_id;
$userid =$calendar->user_id;
$title=$calendar->title;
$description=$calendar->description;
$output = array('success' => true, 'calendar_id' => $calender_id, 'user_id' => $userid, 'title' => $title, 'description' => $description);
//$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
return $this->redirect()->toRoute('calendar');
}
}
return array('form' => $form);
}
else
{
$this->redirect()->toRoute('zfcuser/login');
}
}
how i get last inserted id?
If your calendarTable extends TableGateway you can use $calendarTable->getLastInsertValue() to get the last insert id. You can also use this method in your saveCalendar method.