Codeigniter Bootstrap Markdown textarea - PullRequest
       18

Codeigniter Bootstrap Markdown textarea

0 голосов
/ 16 ноября 2018

У меня проблемы с реализацией Bootstrap Markdown в Codeignitor 3.1.9. Я получаю его, чтобы передать и отобразить данные из запроса в представлении просто прекрасно, если это просто в form_input (). Проблема возникает, когда я пытаюсь опубликовать данные из form_textarea (), подключенной к Bootstrap Markdown с id = "bs-markdown"

Вот часть представления:

                    <div class="card-body"> 
                    <?php echo form_open(site_url("admin/edit_user/".$user->id."/"));?>                 
                    <div class="form-row">
                      <div class="form-group col-md-4">
                        <?php echo lang('edit_user_fname_label', 'first_name', array('class' => 'form-label'));?>
                        <?php echo form_input($first_name, 'first_name' , array('class' => 'form-control', 'id' => 'first_name'));?>
                      </div>
                      <div class="form-group col-md-4">
                        <?php echo lang('edit_user_lname_label', 'last_name', array('class' => 'form-label'));?>
                        <?php echo form_input($last_name, 'last_name' , array('class' => 'form-control', 'id' => 'last_name'));?>
                      </div>
                      <div class="form-group col-md-4">
                        <?php echo lang('edit_user_company_label', 'company', array('class' => 'form-label'));?>
                        <?php echo form_input($company, 'comnpany' , array('class' => 'form-control', 'id' => 'company'));?>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="form-group col-md-4">
                        <?php echo lang('edit_user_vat_label', 'vat', array('class' => 'form-label'));?>
                        <?php echo form_input($vat, 'vat' , array('class' => 'form-control', 'id' => 'vat'));?>
                      </div>
                      <div class="form-group col-md-4">
                        <?php echo lang('edit_user_email_label', 'email', array('class' => 'form-label'));?>
                        <?php echo form_input($email, 'email' , array('class' => 'form-control', 'id' => 'email'));?>
                      </div>
                      <div class="form-group col-md-4">
                        <?php echo lang('edit_user_phone_label', 'phone', array('class' => 'form-label'));?>
                        <?php echo form_input($phone, 'phone' , array('class' => 'form-control', 'id' => 'phone'));?>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="form-group col-md-12"">
                        <label class="form-label">Status</label>
                        <select class="custom-select">
                          <option selected="">Active</option>
                          <option>Suspended</option>
                        </select>
                      </div>
                    </div>
                </div>
              </div>                  
              <div class="col-md-8 col-lg-12 col-xl-6">
                <h6 class="card-header">Notes on Customer</h6>    
                <div class="card-body py-0 px-0">                   
                    <?php echo form_textarea('notes',$notes, array('id' => 'bs-markdown'));?>
                </div>                  
              </div>                  
            </div>    
        </div>
        <?php echo form_hidden('id', $user->id);?>
        <?php echo form_hidden($csrf); ?>
        <div class="text-right mt-3">
          <input type="submit" name="submit" value="Update" class="btn btn-primary">
        </div>

        <?php echo form_close();?>
      </div>
      <!-- / Content -->

      <script>
          // Bootstrap Markdown
          $(function() {
            $('#bs-markdown').markdown({
              iconlibrary: 'fa',
              footer: '<div id="md-character-footer"></div><small id="md-character-counter" class="text-muted">600 character left</small>',

              onChange: function(e) {
                var contentLength = e.getContent().length;

                if (contentLength > 600) {
                  $('#md-character-counter')
                    .removeClass('text-muted')
                    .addClass('text-danger')
                    .html((contentLength - 600) + ' character surplus.');
                } else {
                  $('#md-character-counter')
                    .removeClass('text-danger')
                    .addClass('text-muted')
                    .html((600 - contentLength) + ' character left.');
                }
              },
            });

            // Update character counter
            $('#markdown').trigger('change');


            // *******************************************************************
            // Fix icons

            $('.md-editor .fa-header').removeClass('fa fa-header').addClass('fas fa-heading');
            $('.md-editor .fa-picture-o').removeClass('fa fa-picture-o').addClass('far fa-image');
          });
      </script>   

Вот контроллер:

/**
 * Edit a user
 *
 * @param int|string $id
 */
public function edit_user($id)
{
    // Retrieves the operating Users data as Object wich is passed to _navbar
    $this->data['operator'] = $this->ion_auth->user()->row();

    $user = $this->ion_auth->user($id)->row();

    // validate form input
    $this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'trim|required');
    $this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'trim|required');
    $this->form_validation->set_rules('phone', $this->lang->line('edit_user_validation_phone_label'), 'trim|required');
    $this->form_validation->set_rules('email', $this->lang->line('edit_user_validation_email_label'), 'trim|required');

    if (isset($_POST) && !empty($_POST))
    {

        // do we have a valid request?
        if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
        {
            show_error($this->lang->line('error_csrf'));
        }

        if ($this->form_validation->run() === TRUE)
        {


            //echo var_dump($_POST);
            //exit();

            $data = array(
                'first_name' => $this->input->post('first_name'),
                'last_name' => $this->input->post('last_name'),
                'company' => $this->input->post('company'),
                'phone' => $this->input->post('phone'),
                'email' => $this->input->post('email'),
                'notes' => $this->input->post('bs'),


            );


            // check to see if we are updating the user
            if ($this->ion_auth->update($user->id, $data))
            {
                // redirect them back to the admin page if admin, or to the base url if non admin
                $this->session->set_flashdata('message', $this->ion_auth->messages());
                redirect('admin/edit_user/'.$id, 'refresh');    

            }
            else
            {
                // redirect them back to the admin page if admin, or to the base url if non admin
                $this->session->set_flashdata('message', $this->ion_auth->errors());
                redirect('admin/edit_user/'.$id, 'refresh');

            }

        }
    }   

    // set the flash data error message if there is one
    $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

    // pass the user to the view
    $this->data['user'] = $user;        

    $this->data['first_name'] = array(
        'name'  => 'first_name',
        'id'    => 'first_name',
        'type'  => 'text',
        'value' => $this->form_validation->set_value('first_name', $user->first_name),

    );
    $this->data['last_name'] = array(
        'name'  => 'last_name',
        'id'    => 'last_name',
        'type'  => 'text',
        'value' => $this->form_validation->set_value('last_name', $user->last_name),
    );
    $this->data['company'] = array(
        'name'  => 'company',
        'id'    => 'company',
        'type'  => 'text',
        'value' => $this->form_validation->set_value('company', $user->company),
    );
    $this->data['vat'] = array(
        'name'  => 'vat',
        'id'    => 'vat',
        'type'  => 'text',
        'value' => $this->form_validation->set_value('vat', $user->vat),
    );
    $this->data['email'] = array(
        'name'  => 'email',
        'id'    => 'email',
        'type'  => 'text',
        'value' => $this->form_validation->set_value('email', $user->email),
    );
    $this->data['phone'] = array(
        'name'  => 'phone',
        'id'    => 'phone',
        'type'  => 'text',
        'value' => $this->form_validation->set_value('phone', $user->phone),
    );

    $this->data['notes'] = $user->notes;        

    // display the edit user form
    $this->data['csrf'] = $this->_get_csrf_nonce();


    // VIEW: PARTIALS & TEMPLATE
    $partials['_dev_bar']  = $this->load->view('_dev_bar', NULL, TRUE);     
    $partials['navbar']    = $this->load->view('admin/modules/_navbar', $this->data, TRUE);             
    $partials['sidenav']   = $this->load->view('admin/modules/_sidenav', NULL, TRUE);
    $partials['content']   = $this->load->view('admin/modules/_body-user-customer-edit', NULL, TRUE);
    $partials['bottomnav'] = $this->load->view('admin/modules/_bottomnav', NULL, TRUE);
    $this->load->view('admin/_admin-template', $partials);
}   


/**
 * @return array A CSRF key-value pair
 */
public function _get_csrf_nonce()
{
    $this->load->helper('string');
    $key = random_string('alnum', 8);
    $value = random_string('alnum', 20);
    $this->session->set_flashdata('csrfkey', $key);
    $this->session->set_flashdata('csrfvalue', $value);

    return array($key => $value);
}

/**
 * @return bool Whether the posted CSRF token matches
 */
public function _valid_csrf_nonce(){
    $csrfkey = $this->input->post($this->session->flashdata('csrfkey'));
    if ($csrfkey && $csrfkey === $this->session->flashdata('csrfvalue')){
        return TRUE;
    }
        return FALSE;
}

public function redirectUser(){
    if ($this->ion_auth->is_admin()){
        redirect('admin', 'refresh');
    }
    redirect('/', 'refresh');
}

var_dump ($ Post) показывает, что заметки даже не публикуются в массиве:

array(9) { 
   ["first_name"]=> string(7) "Johnwww" 
   ["last_name"]=> string(5) "Ddddd" 
   ["company"]=> string(0) "" 
   ["vat"]=> string(0) "" 
   ["email"]=> string(12) "john@doe.com" 
   ["phone"]=> string(8) "07009090" 
   ["id"]=> string(1) "3" 
   ["91EnDeLb"]=> string(20) "0ibAqJsuo9mkVzKlRrEy" 
   ["submit"]=> string(6) "Update" 
}

Если я опускаю ссылку на уценку начальной загрузки как id = "bs-markdown" в текстовой области представления их, var_dump () включает в себя элемент ["notes"] => string (5) "notes"

Любой указатель о том, как действовать, будет оценен.

1 Ответ

0 голосов
/ 17 ноября 2018

Лучшее решение, которое я мог бы придумать (и вы можете найти лучше), это сделать:

$('form').on('submit', function(e){
 var textarea = $('#bs-markdown');
 var value = $('#bs-markdown').data('markdown').getContent();
 $('#some_hidden_field').attr('value', value);
});

Где some_hidden_field - пустое скрытое поле.

Применение этого значения bs-markdown ничего не дало в посте.

Но опять же, я бы предложил использовать другой, более активно поддерживаемый редактор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...