I have a list of bookings and I want to delete them using multiple checkboxes. Here is my code:
foreach ($bookings as $booking): ?>
<tr>
<td><?php echo h($booking['Booking']['first_name']); ?> </td>
<td><?php echo h($booking['Booking']['surname']); ?> </td>
<td><?php echo h($booking['Booking']['created']); ?> </td>
<td><?php echo $this->Form-> checkbox('Bookings.ID.['.$booking['Booking']['ID'].']',
array('value' => $booking['Booking']['ID']));?></td>
</tr>
<?php endforeach; ?>
and in my controller I use this function to delete the selected bookings:
public function deletebooking(){
$bookings = $this->Booking->find('all');
$this->set('bookings',$bookings);
if(!empty($this->data)){
foreach($this->data[Bookings] as $key => $value){
if($value != 0){
$this->Booking->delete($value);
$this->redirect(array('action' => 'index'));
}
}
}
}
Can anyone tell me why it is not working?
Change your input field to the following:
foreach ($bookings as $booking): ?>
<td>
<?php echo $this->Form->checkbox('bookingids',
array(
'value' => $booking['Booking']['ID'],
'name' => 'data[Booking][bookingids][]',
));?>
</td>
Notice the empty [] in the name value. This will create a new index of that array. In your controller you would access it like this:
if(!empty($this->data)) :
foreach($this->data['Bookings']['bookingids'] as $key => $value):
$data = array();
$data['Booking']['id'] = $value;
$this->Booking->delete($data);
endforeach;
$this->redirect(array('action' => 'index'));
endif;
Related
I am trying to save a schedule of working days on a table multiple rows at once...
I am doing this wrong, still giving me errors.
I have seen tabular inputs from others, but can't get this right.
I really need some other eyes on it.
I have a similar problem as https://phppedia.com/en/knowledge-base/32481399/yii2-insert-multiple-records-of-a-same-table
model:
public
function rules()
{
return [
['store_id', 'string'],
['day', 'string'],
['start_hour', 'string'],
['end_hour', 'string'],
['holiday','boolean'],
];
}
controler:
public function actionCreate()
{
$count = count(Yii::$app->request->post('Openhour', []));
$model = [new Openhours()];
for ($i = 1; $i < $count; $i++) {
$model[] = new Openhours();
}
if ($model->loadMultiple($model, Yii::$app->request->post())) {
foreach ($model as $model) {
$model->save(false);
}
}
return $this->render('create', ['model' => $model,]);
}
_form
<?php $stores = Stores::getAll() ?>
<?php foreach ($stores as $store): ?>
<?php if ($store->id !== 0): ?>
<?php $listData[$store->id] = [$store->id => $store->title]; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true, 'options' => ['class' => 'model-form'],]); ?>
<?php foreach ($model as $index => $model): ?>
<div class="row row-cols-3">
<div class="col">
<h5>
<?php if ($store->title === Yii::$app->user->identity->username) : ?>
<?= $form->field($model, '[$index]store_id')->hiddenInput(['value' => $store->title])->label($store->title) ?>
<?php else: ?>
<?= $form->field($model, '[$index]store_id')->dropDownList($listData, ['prompt' => 'Select...']); ?>
<?php endif; ?>
</h5>
</div>
<div class="col">Opening</div>
<div class="col">Close</div>
</div>
<?php $days = Storedays::getAll() ?>
<?php foreach ($days as $day): ?>
<div class="row row-cols-3">
<div class="col">
<div class="row justify-content-between">
<div class="col">
<h6><?= $day->name ?></h6>
<?= $form->field($model, '[$index]day')->hiddenInput(['value' => $day->name, 'id' => 'day' . $day->id])->label(false) ?>
</div>
<div class="col">
<?= $form->field($model, '[$index]holiday')->checkbox(['selected' => $model->holiday, 'id' => 'holiday' . $day->id])->label(false) ?>
</div>
</div>
</div>
<div class="col">
<?= $form->field($model, '[$index]start_hour')->Input('text')->widget(TimePicker::class, ['options' => ['id' => 'start_hour' . $day->id], 'pluginOptions' => ['maxHours' => '8', 'template' => 'dropdown', 'showSeconds' => false, 'showMeridian' => false, 'minuteStep' => 15,]])->label(false) ?>
</div>
<div class="col">
<?= $form->field($model, '[$index]end_hour')->Input('text')->widget(TimePicker::class, ['options' => ['id' => 'end_hour' . $day->id], 'pluginOptions' => ['maxHours' => '8', 'template' => 'dropdown', 'showSeconds' => false, 'showMeridian' => false, 'minuteStep' => 15,]])->label(false) ?>
</div>
</div>
<?php endforeach; ?>
<?php if (IS_ROOT) : ?><?= $form->field($model, '[$index]slug') ?><?php endif; ?>
<?= Html::submitButton('save', ['class' => 'btn btn-primary']) ?>
<hr class="mb-3">
<?php endforeach; ?>
<?php ActiveForm::end(); ?>
First you have an array of objects and you must use plural name instead.
So model become models.
Second you must use functions for loading multiple models from request Model::loadMultiple($models) and for validate multiple models Model::validateMultiple($models).
Now in your controller:
public function actionCreate()
{
$count = count(Yii::$app->request->post('Openhour', []));
$models = [new Openhours()];
for ($i = 1; $i < $count; $i++) {
$models[] = new Openhours();
}
if (Model::loadMultiple($models, Yii::$app->request->post()) && Model::validateMultiple($models)) {
foreach ($models as $model) {
$model->save(false);
}
}
return $this->render('create', ['models' => $models]);
}
Now in your _form.php change the line:
<?php foreach ($model as $index => $model): ?>
To:
<?php foreach ($models as $index => $model): ?>
I am working on my collage project in which admin can create Employees(Teachers) and teachers can create students now my problem is that in index and view file any employee can see the total list of students recently added.
i want to put condition on view/index file so that specific teacher can view list of students created by him or her.
i have link between user table and Employee table (Created by & updated by)
Regards,
Yuvraj Verma
<section class="content doc-user-profile">
<div class="col-md-12 text-center">
</div>
</div>
<table class="table table-striped">
<tr>
<th><?= $info->getAttributeLabel('stu_unique_id') ?></th>
<td><?= Html::encode($info->stu_unique_id) ?></td>
</tr>
<tr>
<th><?php echo Yii::t('stu', 'Name'); ?></th>
<td><?= Html::encode($this->title) ?></td>
</tr>
<tr>
<th><?= $info->getAttributeLabel('stu_email_id') ?></th>
<td><?= Html::encode($info->stu_email_id) ?></td>
</tr>
<tr>
<th><?= $info->getAttributeLabel('stu_mobile_no') ?></th>
<td><?= $info->stu_mobile_no ?></td>
</tr>
<tr>
<th><?php echo Yii::t('stu', 'Status'); ?></th>
<td>
<?php if($model->is_status==0) : ?>
<span class="label label-success"><?php echo Yii::t('stu', 'Active'); ?></span>
<?php else : ?>
<span class="label label-danger"><?php echo Yii::t('stu', 'InActive'); ?></span>
<?php endif; ?>
</td>
</tr>
</table>
</div>
<div class="col-lg-9 profile-data">
<ul class="nav nav-tabs responsive" id = "profileTab">
<li class="active" id = "personal-tab"><i class="fa fa-street-view"></i> <?php echo Yii::t('stu', 'Personal'); ?></li>
</ul>
<div id='content' class="tab-content responsive">
<div class="tab-pane active" id="personal">
<?= $this->render('_tab_stu_personal', ['info' => $info, 'model' => $model]) ?>
</div>
</div>
</div>
</div> <!---End Row Div--->
Student Create Controller is as below:
public function actionCreate()
{
$model = new StuMaster();
$info = new StuInfo();
$user =new User();
$auth_assign = new AuthAssignment();
if (Yii::$app->request->isAjax) {
if($info->load(Yii::$app->request->post())) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($info);
}
if($model->load(Yii::$app->request->post())) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
$stud_uniq_no = \app\modules\student\models\StuInfo::find()->max('stu_unique_id');
$uniq_id = NULL;
if(empty($stud_uniq_no)) {
$uniq_id = $info->stu_unique_id = 1;
}
else {
$chk_id = StuInfo::find()->where(['stu_unique_id' => $stud_uniq_no])->exists();
if($chk_id)
$uniq_id = $stud_uniq_no + 1;
else
$uniq_id = $stud_uniq_no;
}
if ($model->load(Yii::$app->request->post()) && $info->load(Yii::$app->request->post()))
{
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($info);
}
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
$model->attributes = $_POST['StuMaster'];
$info->attributes = $_POST['StuInfo'];
$info->stu_dob = Yii::$app->dateformatter->getDateFormat($_POST['StuInfo']['stu_dob']);
if(empty($_POST['StuInfo']['stu_email_id']))
$info->stu_email_id = NULL;
else
$info->stu_email_id = strtolower($_POST['StuInfo']['stu_email_id']);
$login_id = \app\models\Organization::find()->one()->org_stu_prefix.$uniq_id;
$user->user_login_id = $login_id;
$user->user_password = md5($user->user_login_id.$user->user_login_id);
$user->user_type = "S";
$user->created_by = Yii::$app->getid->getId();
$user->created_at = new \yii\db\Expression('NOW()');
if($info->save(false))
{
$user->save(false);
}
$model->stu_master_stu_info_id = $info->stu_info_id;
$model->stu_master_user_id = $user->user_id;
$model->created_by = Yii::$app->getid->getId();
$model->created_at = new \yii\db\Expression('NOW()');
$model->save(false);
$s_info = StuInfo::findOne($model->stu_master_stu_info_id);
$s_info->stu_info_stu_master_id = $model->stu_master_id;
$s_info->save(false);
$auth_assign->item_name = 'Student';
$auth_assign->user_id = $user->user_id;
$auth_assign->created_at = date_format(date_create(),'U');
$auth_assign->save(false);
if ($model->save()) {
return $this->redirect(['view', 'id'=>$model->stu_master_id]);
}
else
return $this->render('create', ['model' => $model, 'info' => $info, 'uniq_id'=>$uniq_id]);
} else {
return $this->render('create', [
'model' => $model, 'info' => $info, 'uniq_id'=>$uniq_id
]);
}
}
In your "modelSearch"'s search function add a created_by filter:
public function search($params)
{
$query = StuInfo::find();
...
$query->andFilterWhere(['created_by' => Yii::$app->user->identity->id]);
....
}
For your view(actionView) you could check if the record was created by the logged in user before render.
This would get complex with time so i recommend using authorization - Yii2 Access Control and Authorization
Your create action is ok.
You have to put restriction in index/view action of your controller
Your index action should be like this
public function actionIndex()
{
$searchModel = new StudentSearch();
$query = Student::find()->where(['teacher_id'=>$logged_teacher_id_from_session]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 20,
],
'sort' => [
'defaultOrder' => [
'student_id' => SORT_ASC,
]
],
]);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
In this case teacher who is logged in can see only his/ student
I have joined 2 table, now I want to show the name of categories in field <th>Categories name</th>. How can I do that with <?php foreach ($posts as $post){ ?> ? Do i render like <?=$post->categories.name?> ? I'm stuck here.
Thank you.
My controller:
public function actionIndex()
{
$query = posts::find()->leftJoin('categories', 'posts.cate_id = categories.id');
$cates = Categories::find()->all();
$posts= $query->orderBy(['create_date' => SORT_DESC])->all();
$images = Images::find()->all();
$searchModel = new PostsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'posts' => $posts,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'cates' => $cates,
'images' => $images,
]);
}
My view:
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Create Date</th>
</thead>
<tbody>
<?php foreach ($posts as $post){ ?>
<tr>
<td><?= $post->id ?></td>
<th><?= Html::a($post->name, ['post/view', 'id'=>$post->id]) ?></th>
<td><?= $post->create_date ?></td>
</tr>
<?php } ?>
</tbody>
Loop through the categories just as with posts. Its the same principle.
foreach($posts as $post)
foreach($post->categories as $category)
echo $category->name;
This is based on the assumption you have defined the proper relations in the model.
I.e. through foreign key:
public function getCategories()
{
return $this->hasMany(Category::className(), ['post_id' => 'id']);
}
You seem to have it the other way around. You can have category_id in post, but then its limited to one category. Unless, you store the ids in the field seperated by a delimeter. But that option requires a bit more work.
i want captcha code security in my signup page but when i fill the form with wrong captcha code and submit form. problem is view two page in my signup page. and fill this form again with correct captcha but they same problem again and show incorrect captcha.
CONTROLLER
public function user_signup($data = NULL){
$this->load->library('form_validation');
$this->recaptcha->recaptcha_check_answer($_SERVER['REMOTE_ADDR'],$this->input->post('recaptcha_challenge_field'),$this->input->post('recaptcha_response_field'));
$this->form_validation->set_rules('Username', 'Username', 'required|trim|is_unique[users.Username]');
$this->form_validation->set_rules('First_name', 'First Name', 'required|trim');
$this->form_validation->set_rules('Last_name', 'Last Name', 'required|trim');
$this->form_validation->set_rules('Email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('Password', 'Password', 'required|trim|md5');
$this->form_validation->set_rules('Conf_password', 'Confirm Password', 'required|trim|matches[Password]');
$this->form_validation->set_message('is_unique', 'Username already exists.');
if($this->form_validation->run() && $this->recaptcha->getIsValid()){
//Call to recaptcha to get the data validation set within the class.
$form_data = array();
$form_data['Username'] = $this->input->post('Username');
$form_data['First_name'] = $this->input->post('First_name');
$form_data['Last_name'] = $this->input->post('Last_name');
$form_data['Email'] = $this->input->post('Email');
$form_data['Password'] = $this->input->post('Password');
$form_data['Conf_password'] = $this->input->post('Conf_password');
$this->load->model('User');
$this->User->sign_up($form_data);
$data['msg']= "Account Created Sucessfuly";
}else{
if(!$this->recaptcha->getIsValid()){
$this->session->set_flashdata('error','incorrect captcha');
}
}
redirect("Users/signup", $data);
}
MODEL
public function sign_up($form_data){
$this->db->insert('users', $form_data);
}
VIEW
<?php
//$val = NULL;
if(isset($results->id)){
$val = "Update";
$action = "Users/user_update/".$results->id;
}else{
$val= "Register";
$action = "Users/user_signup";
}; ?>
<?php echo form_open($action); ?>
<?php echo form_input(array('name'=>'Username', 'class'=>'input-xlarge', 'type'=>'text', 'placeholder'=>'Username', 'required' => 'required', 'value'=>$u)); ?>
<?php echo form_error('Username', '<div class="alert alert-error">', '</div>'); ?>
<?php echo form_input(array('name'=>'First_name', 'class'=>'input-xlarge', 'type'=>'text', 'placeholder'=>'First Name', 'required' => 'required', 'value'=>$f)); ?>
<?php echo form_error('First_name', '<div class="alert alert-error">', '</div>'); ?>
<?php echo form_input(array('name'=>'Last_name', 'class'=>'input-xlarge', 'type'=>'text', 'placeholder'=>'Last Name', 'required' => 'required', 'value'=>$l)); ?>
<?php echo form_error('Last_name', '<div class="alert alert-error">', '</div>'); ?>
<?php echo form_input(array('name'=>'Email', 'class'=>'input-xlarge', 'type'=>'text', 'placeholder'=>'Email', 'required' => 'required', 'value'=>$e)); ?>
<?php echo form_error('Email', '<div class="alert alert-error">', '</div>'); ?>
<?php echo form_input(array('name'=>'Password', 'class'=>'input-xlarge', 'type'=>'password', 'placeholder'=>'Password')); ?>
<?php echo form_error('Password', '<div class="alert alert-error">', '</div>'); ?>
<?php echo form_input(array('name'=>'Conf_password', 'class'=>'input-xlarge', 'type'=>'password', 'placeholder'=>'Confirm Password')); ?>
<?php echo form_error('Conf_password', '<div class="alert alert-error">', '</div>'); ?>
<?php if(!isset($results->id)){echo $recaptcha_html;} ?>
<?php if ($this->session->flashdata('error') !== FALSE) { echo '<div class="alert alert-error">'.$this->session->flashdata('error').'</div>'; } ?>
<div class="login-actions">
<span><input type="checkbox"> <span class="remember">I have read & agree</span></span>
<span><?php echo form_submit(array('value'=>$val, 'class'=>'btn btn-large btn-warning pull-right', 'type'=>'submit')); ?></span>
</div>
<?php echo form_close(); ?>
Put this code after the if(!$this->recaptcha->getIsValid()){ and echo messages...
if($this->input->post('recaptcha_response_field') =="" ){
$this->session->set_flashdata('error','fill up this code');
}else{
$this->session->set_flashdata('error','incorrect captcha');
}
if your show the message "account create successfully". use the set flash message
read this link properly
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
How to display error messages in CodeIgniter
First you create a signup function in Controller and and view default signup page. as like
$this->load->view('User/User_sign_up');
In wordpress, the following function will echo out a list of categories with the posts associated with each category underneath each category name.
This works fine, except for the fact that this produces a flat structure. Some of the categories are child categories other categories, and I'd like to be able to output a list with a structure that matches this (kind of like a site map)
Is anyone able to help me figure out how to modify this code to achieve this?
function posts_by_category() {
//get all categories then display all posts in each term
$taxonomy = 'category';
$param_type = 'category__in';
$term_args=array(
'orderby' => 'name',
'order' => 'ASC'
);
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
foreach( $terms as $term ) {
$args=array(
"$param_type" => array($term->term_id),
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<div class="category section">
<h3><?php echo ''.$term->name;?></h3>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>
</div>
<?php
}
}
}
wp_reset_query(); // Restore global post data stomped by the_post().
}
Here is a code snippet I found the other day Hierarchical Category List with Post Titles, should do the trick.
<?php
/*****************************************************************
*
* alchymyth 2011
* a hierarchical list of all categories, with linked post titles
*
******************************************************************/
// http://codex.wordpress.org/Function_Reference/get_categories
foreach( get_categories('hide_empty=0') as $cat ) :
if( !$cat->parent ) {
echo '<ul><li><strong>' . $cat->name . '</strong></li>';
process_cat_tree( $cat->term_id );
}
endforeach;
wp_reset_query(); //to reset all trouble done to the original query
//
function process_cat_tree( $cat ) {
$args = array('category__in' => array( $cat ), 'numberposts' => -1);
$cat_posts = get_posts( $args );
if( $cat_posts ) :
foreach( $cat_posts as $post ) :
echo '<li>';
echo '' . $post->post_title . '';
echo '</li>';
endforeach;
endif;
$next = get_categories('hide_empty=0&parent=' . $cat);
if( $next ) :
foreach( $next as $cat ) :
echo '<ul><li><strong>' . $cat->name . '</strong></li>';
process_cat_tree( $cat->term_id );
endforeach;
endif;
echo '</ul>';
}
?>