I have related tables and show at gridview. When i want to delete data from gridview, i take the mysql error about this data using other tables field. At that time i want to show message to user for example "This data not deleting".
I did it at yii 1.1 as follows.
views/xxx/index.php
<div id="statusMsg">
<?php if(Yii::app()->user->hasFlash('success')):?>
<div class="flash-success" >
<?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>
<?php if(Yii::app()->user->hasFlash('error')):?>
<div class="flash-error">
<?php echo Yii::app()->user->getFlash('error'); ?>
</div>
<?php endif; ?>
</div>
gridview
array(
'class'=>'CButtonColumn',
'afterDelete'=>
'function(link,success,data){
if(success) $("#statusMsg").html(data);
}',
),
controller/xxxcontroller
public function actionDelete($id)
{
try{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
Yii::app()->user->setFlash('success','Normal – Deleted Successfully');
else
echo "<div class='flash-success'>Yiyecek Başarıyla Silindi</div>";
}catch(CDbException $e){
if(!isset($_GET['ajax']))
Yii::app()->user->setFlash('error','Normal – error message');
else
echo "<div class='flash-error'>Yiyecek silinimedi.</div>"; //for ajax
}
}
but afterDelete not using in yii2 . And i didn't know what to use instead of afterDelete.
Thank you.
I used following code in controller delete action
$connection = Yii::$app->db;
$transaction = $connection->beginTransaction();
try {
$this->findModel($id)->delete();
$transaction->commit();
Yii::$app->session->setFlash('success','Silme işlemi başarılı.');
return $this->redirect(['index']);
} catch (IntegrityException $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error','Silme işleminde hata oluştu.');
return $this->redirect(['index']);
}catch (\Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error','Silme işleminde hata oluştu.');
return $this->redirect(['index']);
}
Related
I want to run a code to send email to all users. At first i used this code to run a test.
->setTo([
'john.doe#gmail.com' => 'John Doe',
'jane.doe#gmail.com' => 'Jane Doe',
])
I found out that the mail is 1 mail sent to multiple recipents, while i need to 2 emails to 2 recipients. Because in reality i need to send to over hundred people at once. SO i try foreach loop.
public function contact($email)
{
$users = Users::find()->all();
$content = $this->body;
foreach($users as $user){
if ($this->validate()) {
Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
return true;
}
}
return false;
}
But it only run 1 loop and end.
Please tell me where i'm wrong.
Thank you
the reason just one mail is sent is the
return true
it returns after the first email is sent, you should use try{}catch(){} like below
public function contact($email) {
$users = Users::find()->all();
$content = $this->body;
try {
foreach ($users as $user) {
if ($this->validate()) {
$r = Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
if (!$r) {
throw new \Exception('Error sending the email to '.$user->email);
}
}
}
return true;
} catch (\Exception $ex) {
//display messgae
echo $ex->getMessage();
//or display error in flash message
//Yii::$app->session->setFlash('error',$ex->getMessage());
return false;
}
}
You can either return false in the catch part or return the error message rather than returning false and where ever you are calling the contact function check it the following way.
if(($r=$this->contact($email))!==true){
//this will display the error message
echo $r;
}
I want update just one column of table I'm getting this error when updating a table rows:
Call to a member function load() on null
This is my action:
public function actionAddNote(){
$id = \Yii::$app->request->post('id');
$model = MainRequest::findOne($id);
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->update()){
echo "1";
}else {
print_r($model->getErrors());
}
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
My model:
class MainRequest extends ActiveRecord {
public static function tableName()
{
return "main_request";
}
public function behaviors()
{
return [
DevNotificationBehavior::className(),
];
}
public function rules() {
return [
[
['who_req',
'req_description',
'req_date',
'extra_note'
], 'safe']
];
}
The form will render properly and I can see my text but when I submit this the error occur:
<div>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'extra_note')->textInput(); ?>
<div class="form-group">
<?= Html::submitButton('save', ['class' => 'btn green']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Can anybody tell what is problem ? Thank you.
You should load the model and the use the model loaded for accessing attribute
and you should manage ythe initial situation where you d0n't have a model to update but need a model for invoke the update render form eg:
public function actionAddNote(){
$myModel = \Yii::$app->request->post();
$model = MainRequest::findOne($myModel->id);
if (isset($model)){
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->update()){
echo "1";
}else {
print_r($model->getErrors());
}
}
} else {
$model = new MainRequest();
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
Use Simple save function or updateAttributes of Yii2:
public function actionAddNote(){
$id = \Yii::$app->request->post('id');
$model = MainRequest::findOne($id);
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->**save**()){
echo "1";
}else {
print_r($model->getErrors());
}
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
I have 2 tables:
Events and Registration.
Events Fields: EventID and EventName
Registration Field: MemberID and Name
I want to pull the EventName and the Name- of the person. How do I do this with a model?
The code I have:
Model
function getAll()
{
$query = $this->db->get('tblRegistration');
if( $query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
}
$query->free_result();
return $data;
}
controller
public function getallevents() {
$this->load->model('events_model');
$data['records'] = $this->events_model->getAll();
$this->load->view('view-events', $data);
}
View
foreach ($records as $row):
echo "<tr>";
echo "<td> $row->Name</td>";
// echo "<td> $row->intLocationID</td>";
echo "</tr>";
endforeach;
Edit
OK I have added the data that I want out of the table.
model
function getAll()
{
// get all the records from the schools table
$this->db->select('*');
$this->db->from('tblRegistration as reg');
$this->db->join('tblMeetRace as met', 'reg.intMeetRaceID = met.intEventID');
$query = $this->db->get();
// if the number of rows returned is more than 0
if( $query->num_rows() > 0) {
// loop through each record (row) and place that
// record into an array called $data
foreach ($query->result() as $row) {
$data[] = $row;
}
}
$query->free_result();
// return the array to the controller
return $data;
}
view
foreach ($records as $row):
echo "<tr>";
echo "<td> $row->intMeetRaceID/td>";
echo "<td> $row->intEventID</td>";
echo "</tr>";
endforeach;
but I get an error of:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/view-events.php
Line Number: 89
First of all you need to add another column in your events table for storing the MemberId, say memberid.
Once you have that, when ever a member registers for an event, you can store his ID in the events table and relate it.
Then you can use Joins to fetch the datas
$this->db->select('*');
$this->db->from('registration as reg');
$this->db->join('events as evt', 'reg.id = evt.memberid');
$query = $this->db->get();
Im trying to get it so when you press a button it updates the value of 'subscribe' to 1 but for some reason its not working.
<?php
session_start();
$userid = $_SESSION['userID'];
$username = $_SESSION['username'];
require '../../core/connect.php';
if ($_SESSION['userID']) {
if (isset($_POST['subscribe'])) {
$query2 = mysql_query("UPDATE `users` SET `subscribe`='1' WHERE `username`='".$username."'") or die(mysql_error());
if ($query2) {
header("Location: /index.php");
} else {
echo "An error occured. Your subscription failed! Please try again later.";
}
}else {
echo "Error occured.";
}
}else {
echo "No session found.";
}
?>
The error im getting is the 'Error occured.'
The field is an int with the default value as 0
Thanks!
'Error Occurred' implies
if(isset($_POST['subscribe'])) // is evaluating to false
use
print_r($_POST) // and post the result
if(isset($_SESSION['subscribe']))
where am i going wrong in my extraction of country name from mysql database? (codeigniter: activerecord enabled)
Its printing out "default country" instead of expected "Australia".
Pages Controller
public function view($page)
{
$page = strtoupper($page); // Capitalize the first letter
$data = array(
'title' => 'My Title',
'country' => 'default country'
);
$this->getCountryName($page, $data);
if(!is_null($data['country'])){
$page = "country";
}
$this->load->helper('url');
$this->load->helper('utility');
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
if(!is_null($data['country'])){
$this->load->view('templates/infobox', $data);
}
$this->load->view('templates/footer', $data);
}
function getCountryName(&$page, &$data){
$this->db->select('name')->from('pv_country')->where('code', $page);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data['country'] = $row;
echo $row;
}
}
}
Country View
<div style =" position:absolute;top:90%; background: red;">
<?php echo $country; ?></div> // prints default country.
</div>
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: pages/country.php
Line Number: 25
so i put in some more debugging and found the correct syntax/method to call to get the result,
which then returns an object with attributes that need to be accessed in the view.
function getCountryName(&$page, &$data){
$this->db->select('name')->from('pv_country')->where('code', $page);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['country'] = $query->row();
}
}
<?php echo $country->name; ?>